Audio.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. const fillIn = val => `${val < 10 ? '0' : ''}${val}`,
  2. formatTime = _time => {
  3. let time = Math.round(_time);
  4. let second = Math.round(time % 60),
  5. minute = Math.floor(time / 60 % 60),
  6. 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. 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. option = _ts.option;
  21. let audio = _ts.audio = wx.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;