连续重现 4 个声音 JavaScript
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 );
}
我有一组音频,如下所示:
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 );
}