简体   繁体   中英

How can I play the audio successively with PhoneGap?

I have several Media file to play. But they have to be played one by one. like:

var play_media;
play_media= new Media("../record/01.mp3",Success,Error);
play_media.play();
//And as the `../record/01.mp3` media file is done. 
//I will release it and create another one to play. 
play_media= new Media("../record/02.mp3",Success,Error);

But it seems that as one media's play is done, it returns nothing.
How can I do ?

Try something like this:

var media = {"../record/01.mp3","../record/02.mp3","../record/03.mp3"};
var next = 0, play_media;
for(int i=0; i<media.lenght; i++){
    play_media= new Media(media[next]);
    play_media.play();
    if(soundTimer == null){
        soundTimer = setInterval(function(){
            vpSound.getCurrentPosition(
                function(position){
                    if(position > -1){
                        //Do something if you want 
                    }
                }
            );
        }, 1000);
        next = next + 1;
    }
}

First find the audio clip length with media.getDuration: and use setTimeout Function to play next song. In this way you will be able play multiple songs continuously

Use the Media.getCurrentPosition() along with the javascript setInterval and set it to interval every second (1000) to get the position of the track being played.Then check if the position of the track is equal to -0.001 and this means that it has ended. From there you can move onto the next track or if it is the last track use Media.release()

           var mediaTimer = setInterval(function () {
               media.getCurrentPosition(function (position) {
                     if (position > -0.001) {
                        //Do something like update a progress bar and set times.
                     }
                     else if (position === -0.001) {
                           selectedIndex = selectedIndex + 1; //selectedIndex is the index of the song chosen in a list.
                          if (selectedIndex > playlistLength) {
                              media.release();
                          } 
                          else {
                            var nextTrack = app.FolderList.tracks[selectedIndex]; //get the next track from a list of tracks using the selectedIndex
                            playPause(nextTrack.SongPath);//playPause() is used to initialize a new Media object with the new track and then plays it.
                          }
                     },
                     function () {
                     console.log('Unable to retrieve media position: ' + error.code);
                       });
                    },
                    1000);

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