簡體   English   中英

在鏈式JavaScript中重現4種聲音

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM