[英]Reproduce 4 sounds in chain JavaScript
我有一系列的音频,看起来像这样:
let pentagram = [
{
sound: new Audio('somePathtoAudio.wav')
},
{
sound: new Audio('somePathtoAudio.wav')
},
{
sound: new Audio('somePathtoAudio.wav')
},
{
sound: new Audio('somePathtoAudio.wav')
}
];
而且我需要重现这4个音频,每个人连续1秒重现所有音频。
function play() {
pentagrama[0].audio.play();
pentagrama.forEach((part, i) => {
setTimeout(() => {
part.audio.pause();
part.audio.currentTime = 0;
if (i + 1 < pentagrama.length) pentagrama[i + 1].audio.play();
}, (i + 1) * 1000);
});
}
这是我所做的,但我并不真正喜欢它,它可以工作,但是有更好的方法吗? 因为我一直在寻找看起来更优雅的东西,但我还没有发现。
是的,有更好的方法-使用SoundPlayer.js !
加载SoundPlayer :
<script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/SoundPlayer.js"></script>
这将很容易!
const player = new SoundPlayer();
function play () {
player.load( 'sound1.mp3' ).play( 1 );
player.load( 'sound2.mp3' ).play( 2 );
player.load( 'sound3.mp3' ).play( 3 );
player.load( 'sound4.mp3' ).play( 4 );
}
传递给播放的数字是秒,直到播放为止。
编辑
如果您只想播放声音1秒钟,请使用:
const player = new SoundPlayer();
function play () {
player.load( 'sound1.mp3' ).play( 1, 1 );
player.load( 'sound2.mp3' ).play( 2, 1 );
player.load( 'sound3.mp3' ).play( 3, 1 );
player.load( 'sound4.mp3' ).play( 4, 1 );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.