[英]Reproduce 4 sounds in chain JavaScript
I have an array of Audios that look like this: 我有一系列的音频,看起来像这样:
let pentagram = [
{
sound: new Audio('somePathtoAudio.wav')
},
{
sound: new Audio('somePathtoAudio.wav')
},
{
sound: new Audio('somePathtoAudio.wav')
},
{
sound: new Audio('somePathtoAudio.wav')
}
];
And i need to reproduce this 4 audios that reproduces everyone for 1 second one after each other. 而且我需要重现这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);
});
}
This is what i've done and i dont really like it, it works, but is there a better way? 这是我所做的,但我并不真正喜欢它,它可以工作,但是有更好的方法吗? Because i've been looking for something that looks more elegant and i haven't found that.
因为我一直在寻找看起来更优雅的东西,但我还没有发现。
Yes there is a better way - using SoundPlayer.js ! 是的,有更好的方法-使用SoundPlayer.js !
Load SoundPlayer : 加载SoundPlayer :
<script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/SoundPlayer.js"></script>
And this will be easy! 这将很容易!
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 );
}
Where the number passed to play is seconds until it will be played. 传递给播放的数字是秒,直到播放为止。
EDIT 编辑
If you want the sound to only be played for 1 second, use: 如果您只想播放声音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.