简体   繁体   中英

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.

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 !

Load 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:

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 );

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM