I'm trying to write small website that can stream audio online(radio station) and got few questions: 1. Do i have to index all my music files into database, or i can randomily pick file from file system and play it. 2. When should i use ajax to load new song(right after last finished, or few seconds before to get responce from server with link to file?) 3. Is it worth to use ajax, or better make list, that will play its full time and then start over?
I think you are asking the wrong Questions.
Regarding the streaming I aggree with @Tigraine
Now,
Single song play:
1 if you want to play an individual song then in your ajax call to action return a key value pair in json response which contains the audio URL of requested song.
For Playlist:
2. You should return an array which contains the audio URL in the same arrangement as they were added into playlist.
Then in your java script declare variable
var current_song
var total_song
In js audio player we commonly have methods which detects when the song completes and then on song complete you can increment the song counter as
current_song+=0
when the counter reaches to end reset it to one:
Sample code is:
Here I am using Jplayer you can use any other player which one of the best and fully customizable player.
var current_song = 0;
var total_songs;
var song_id_array;
$.ajax({
url:"<%=url_for :controller => 'cont_x',:action => 'song_in_playlist'%>",
data:'playlist_id=' + encodeURIComponent(playlist_id),
cache:false,
success:function (data) {
song_id_array = data.array; //data.array variable contain's the audio URL's array of songs inside selected playlist which is returned by the action //
total_songs = song_id_array.length;
}
})
current_song = 0;
play_right_song(current_song);
}
function play_right_song(current_song) {
$("#jquery_jplayer_1").jPlayer("destroy");
var audio_url_inside = song_id_array[current_song];
$('#jquery_jplayer_1').jPlayer({
ready:function (event) {
$(this).jPlayer("setMedia", {
mp3:audio_url_inside
}).jPlayer("play");
},
ended:function () { // The $.jPlayer.event.ended event
current_song += 1;
if (current_song >= total_songs) {
current_song = 0;
}
play_right_song(current_song);
},
swfPath:"<%= asset_path('Jplayer.swf')%>",
supplied:"mp3"
});
}
and if you want to handle next and previous song in playlist just ask for the code. I will update the answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With