react-nativereact-native-sound

Sequentially play an array of sounds using react-native-sound


I am using the function below to attempt to play the array (a,b,c are all Sound instances initialised beforehand) of sounds (notes) sequentially (a is played and ends, then b is played and ends etc.). However instead of playing each sound one after the other it is playing all the sounds together in one go. How can this code be modified to play the sounds sequentially?

const playSound = () =>{
    const notes = [a,b,c,a]
    notes.forEach(element => {element.setVolume(1).play()});
}

Solution

  • notes.forEach(element => {element.setVolume(1).play()});

    this will play all at the same time, you cant do this

    For that to handle you need a custom class or function which handles and plays the next audio

    For example something like this :

        const MusicHandler = () => {
        
        var musicQueue = [1,2,3,4,5,6,7]
        
        //play current song 
            const playAudio = () => {
            const currentToBePLayed = musicQueue[0];
        if(currentToBePLayed){
         currentToBePLayed.setVolume(1).play()
        }
           
            }
        // remove the first element and then again play song
           const onplaybackComplete  = () => {
        musicQueue.shift()
    playAudio()
        }
        
        }
    

    here you need to add handler , if audio completes for one, then play another one,