How to set the duration of audio

大兔子大兔子 提交于 2019-12-18 09:08:35

问题


I am trying to set the duration of an audio tag using HTML DOM duration property of audio.

I have tried the following but it doesn't seem to work: $('audio')[0].duration = 1;

I've gone through other answers but I couldn't see any which make use of the duration property.

If the duration property is readonly, what other method does it leave me with?


回答1:


You cannot change the duration as it is locked to the original data (which cannot be changed via the audio element).

You can achieve the illusion of a different duration though by making restrictions on play by monitoring the time and pause the audio when a threshold kicks in:

  • Use the timeupdate event and check currentTime against your threshold
  • You can also use requestAnimationFrame to poll the same value and do the same check
  • Or, for super-accurate timing, you need to use Web Audio API, create an audio-buffer for the audio, then use start/stop with the preferred times. This will require CORS requirements to be fulfilled

On the loading side the browser will possibly load the entire file. If you want to control this part you would have to use Media Source Extension which allow you to control the buffering process.




回答2:


sound = new Howl({

    src: ['./assets/audio/classic_bell.mp3'], //you can set the custom path 
                                       **OR** 
    src : ['http://...../your url/mp3file.mp3'], //you can also set the url path to set 
                                                 the audio                                                        loop: true,
  });

//in method where you want to play the sound

 this.sound.play();

 setTimeout(()=> {

      this.sound.stop();

  }, 1000);


来源:https://stackoverflow.com/questions/30697618/how-to-set-the-duration-of-audio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!