Audio.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. const fillIn = (val) => `${val < 10 ? '0' : ''}${val}`;
  2. const formatTime = (_time) => {
  3. let time = Math.round(_time);
  4. let second = Math.round(time % 60);
  5. let minute = Math.floor((time / 60) % 60);
  6. let hour = Math.floor(time / 60 / 60);
  7. return `${fillIn(hour)}:${fillIn(minute)}:${fillIn(second)}`;
  8. };
  9. class Audio {
  10. constructor(obj) {
  11. const _ts = this;
  12. const option = (_ts.option = obj.attrs);
  13. _ts.loop = option.loop === 'true';
  14. _ts.autoplay = option.autoplay === 'true';
  15. _ts.create();
  16. _ts.index = 0;
  17. }
  18. create() {
  19. const _ts = this;
  20. const option = _ts.option;
  21. let audio = (_ts.audio = uni.createInnerAudioContext());
  22. audio.src = option.src;
  23. // 说明可以播放了
  24. audio.onCanplay(function () {
  25. if (_ts.autoplay && !_ts.index) {
  26. _ts.play();
  27. }
  28. if (!_ts.autoplay && !_ts.index) {
  29. _ts.eventCanplay();
  30. }
  31. });
  32. // 更新时间
  33. audio.onTimeUpdate(function () {
  34. //_ts.status = 'update';
  35. _ts.duration = audio.duration;
  36. _ts.currentTime = audio.currentTime;
  37. // 定义播放结束
  38. if (_ts.duration - _ts.currentTime < 0.5) {
  39. _ts.index++;
  40. if (_ts.loop) {
  41. audio.stop();
  42. } else {
  43. _ts.stop();
  44. }
  45. audio.seek(0);
  46. }
  47. _ts.eventTimeUpdate(formatTime(_ts.duration), formatTime(_ts.currentTime));
  48. });
  49. //
  50. audio.onSeeked(function () {
  51. if (_ts.loop) {
  52. _ts.play();
  53. }
  54. });
  55. }
  56. // 播放
  57. play() {
  58. const _ts = this;
  59. _ts.status = 'play';
  60. _ts.audio.play();
  61. _ts.eventPlay();
  62. }
  63. // 暂停
  64. pause() {
  65. const _ts = this;
  66. _ts.status = 'pause';
  67. _ts.audio.pause();
  68. _ts.eventPause();
  69. }
  70. // 停止
  71. stop() {
  72. const _ts = this;
  73. _ts.status = 'stop';
  74. _ts.audio.stop();
  75. _ts.eventStop();
  76. }
  77. // 销毁
  78. destroy() {
  79. const _ts = this;
  80. _ts.stop();
  81. _ts.audio.destroy();
  82. }
  83. eventCanplay() {}
  84. eventTimeUpdate() {}
  85. eventEnded() {}
  86. eventError() {}
  87. eventPause() {}
  88. eventPlay() {}
  89. eventSeeked() {}
  90. eventSeeking() {}
  91. eventStop() {}
  92. eventWaiting() {}
  93. }
  94. module.exports = Audio;