简体   繁体   中英

HTML5 audio/jQuery

Started to do some research for creating a rather simple media section for a site and I seem to be running into some problems. I will explain to the best of my ability.

I have a 'play list' which consist of 'links' - li elements atm - that utilizes aJax/PHP to pull data and loads into an audio element. I can pull the data just fine, no problems there.

However my issues arises when a user selects a 'track'.

The intended song plays with no issues, however if the user selects the same song or a different song, the first 'track' continues to play while the 'newer selected' track starts. I essentially can play 10+ tracks at the same time - rather annoying.

i am attempting to stop the first song - either my destroying the audio tag or whatever other method - , and play the newer selected song when the user selects a different 'track'

I think i may understand the problem, I keep creating new instances of audio element without destroying the initial instance. thus, was wondering the best way to look for any previous occurrences of audio and upon detection destroy that instance and create a new one.

Below is some code i am testing with, currently this script runs once the aJax callback = success.

--COMMENTS The below code is in jQuery audio = instances of HTML5 audio arydata = an array that contains data from the PHP script --COMMENTS

I am thinking, I would need to add some code before the below code ran to validate if there is any existing audio elements, but im not sure if that is the best approach.

var audio = new Audio();
audio.src = arydata[1] + ".mp3";
audio.load();
audio.play();

Let me know if anything else is needed.

Found a solution.

I erroneously was creating a new Audio instances every time a user selected a track.

Thus, to fix this issue, I instead created the Audio instance upon the script load. Then once a user selects a track, I then find the Audio instance and load the data to it.

Below is the code.

    var audio = new Audio();

$("#media_player_playlist_wrapper li").click(function(){
    var player = $(audio).get(0);
    player.src = filepath;
    player.load();
    player.play();
});

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