Update the JPlayer MP3 file each time a function is called - javascript

function showAudioFull(id)
{
var url = URL_DIRSCREENAUDIOSHOT+AUDIOSHOT_PREFIX+id+'.mp3';
var myCirclePlayer = new CirclePlayer("#jquery_audioFile",
{
m4a: url
}, {
cssSelectorAncestor: "#cp_container_1"
});
}
I am appending the MP3 link to JPlayer each time I call this function in my JS file.
There will be a set of images with "id". With an onClick() function this showAudioFull() is invoked.
But problem is JPlayer is not updating the mp3 file that is being played. It keeps playing the same audio which I click at the first time.
FYI : Using JPlayer Circle player

What about:
var myCirclePlayer = new CirclePlayer("#jquery_audioFile", {
m4a: url
}, {
cssSelectorAncestor: "#cp_container_1"
});
function showAudioFull(id) {
var url = URL_DIRSCREENAUDIOSHOT + AUDIOSHOT_PREFIX + id + '.mp3';
myCirclePlayer("setMedia", {
mp3: url
});
};
This method (setMedia) is used to define the media to play. The media parameter
is an object that has properties defining the different encoding
formats and a poster image. Source: jPlayer dev guide

Related

Why is my JavaScript Code not playing Music?

I want that my buttons ( Home, About, Blog ) on my website plays some sound or music when someone is clicking on them. Now I tried and tried, but cant find out the error in the javascript code.
<body onload="htmlIsReady()">
<script type="text/javascript">
var audio;
var audioLink;
window.onmessage = function(event) {
if (event.data.data) {
//Passes the audio url to the new variable
audioLink = event.data.data;
//Created a new audio object with the received audio url
audio = new Audio('URL of AUDIO-FILE');
}
};
function htmlIsReady() {
window.parent.postMessage("html_is_ready", "*");
}
//Funcion that plays the audio
function playAudio() {
audio.play.play();
}
</script>
// Button that executes the function that plays the audio everytime it's
clicked
<button class="button" onclick="playAudio()">Play</button>
</body>
You're using audio.play.play(), which should be: audio.play(). However, you also haven't provided any actual proper URL/relative filepath as the audio source and at the moment your audio variable is never actually assigned as a new Audio.
It's not too clear why you're using window.onmessage to obtain the url of the audio file but it won't work no matter what because event.data.data is simply wrong. To obtain the data of a posted message you have to use event.data.
Furthermore here you're assigning the data to a variable called audioLink
audioLink = event.data.data;
but don't actually use it for the instantiation of your HtmlAudioElement audio.
Lastly, audio.play.play(); is wrong. To start playback you simply use the play() method on the audio object - audio.play().
Here's a working example:
var audio;
var audioLink;
function playAudio() {
audio.play();
}
window.onmessage = function(event) {
if (event.data) {
audioLink = event.data;
audio = new Audio(audioLink);
}
};
window.postMessage("https://www.w3schools.com/tags/horse.ogg", "*");
<button class="button" onclick="playAudio()">Play</button>

Get the currently played <audio> file on a page with multiple audio files

I have multiple audio files on a page and I am hoping to get the playing audio file through JQuery.
This is what I tried but it only gets the first one:
var audio = document.querySelector('audio');
audio.addEventListener('play', function() {
console.log($(this));
});
Is it possible for me to get only the audio file on the page that is currently playing?
One approach to this problem would be to query all audio elements in the document, and then iterate over those to find the first instance where ispasued is not truthy:
function getCurrentlyPlayingAudio() {
for(const audio of document.querySelectorAll('audio')) {
if(!audio.paused) {
return audio;
}
}
// return undefined if no such audio element found
}
This solution uses the native querySelectorAll() method to query audio elements, and is therefore not dependant on jQuery.
To then query the 'current playing audio element' after an audio element has started playing, you could use the proposed method in the following way:
document.querySelectorAll('audio').forEach(audio => {
audio.addEventListener('play', () => {
const currentPlaying = getCurrentlyPlayingAudio();
console.log('current playing audio:', currentPlaying);
});
});
Thanks,
I also changed my original answer a bit and that worked.
var audList = document.getElementsByTagName("audio");
for (var i = 0; i < audList.length; i++) {
audList[i].addEventListener("play", onPlay, false);
audList[i].addEventListener("ended", onEnded, false);
}
function onPlay(e) {
console.log(e.target.id + " Well hello there!");
console.log($(this));
};
function onEnded(e) {
console.log(e.target.id + " Left this audio.");
};

How can I make an audio sound play only once using JQuery?

So I have a div that plays an mp3 sound when it is clicked. Instead of playin once. It continues to play over and over again. The snippet of code is:
$(".g-contain").click(function() {
audioElement.play();
});
This may be irrelevant but I figure I should show you the overall code:
/* set no cache */
$.ajaxSetup({ cache: false });
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'https://www.dropbox.com/s/k8xaglyd48vbnq1/pacman_chomp.mp3?dl=1');
audioElement.addEventListener('ended', function() {
this.play();
}, false);
$.getJSON("scripts/data", function(data) {
var html = [];
/* loop through array */
$.each(data, function(index, g) {
$(".container").append(
"<div class='g-details'><div class='name'>" +
g.name + "</div>);
// And finally my click call is here
$(".g-contain").click(function() {
audioElement.play();
});
Not sure why the mp3 file keeps playing when g-contain div is clicked
It's due to this code:
audioElement.addEventListener('ended', function() {
this.play();
}, false);
You attached an event listener to the audio element to re-play when the playing is ended. So once it's played (with click) it will play infinitely.
From the MDN ended event Reference:
ended
The ended event is fired when playback or streaming has stopped
because the end of the media was reached or because no further data is
available.
Just get rid of this code.

preload next song before end of the current song

i have one issue related jplayer. i am using jplayer for play song in my site right now i am fetching song using ajax call and add that song into jplayer playlist and now its working fine
my question is is there any option to ready next song before end of current song because when i try it with less then 1 minute song its working fine but when i have each song duration more then 4 minutes its take 3 to 4 seconds to load new song
this is my code for load song in jpalyer playlist
// for create jplayer and add song in playlist
function play_music(songobj) {
is_play = 1;
// $("#jquery_jplayer_1").jPlayer("destroy");
var playlist_length = songobj.length;
myPlaylist = new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_N"
},songobj, {
playlistOptions: {
enableRemoveControls: true,
autoPlay: true
},
supplied: "oga, mp3",
wmode: "window",
useStateClassSkin: true,
autoBlur: false,
smoothPlayBar: true,
keyEnabled: true,
ended : function(){
if(playlist_length == currlength){
// alert('end playlist');
is_play = 0
location.reload();
}
else{
/*if( == ){
console.log('yesssssss');
}*/
// console.log(play_index[index_key]);
// console.log(playlist_obj[currlength]);
loop = 1;
currlength += 1;
var songindex = song_index[currlength - 1];
var listindex = playlist_obj[index_key];
if(song_index[currlength - 1] == playlist_obj[index_key]){
index_key += 1;
$("#jquery_jplayer_1").jPlayer("pause", 0);
console.log('playlist over start next');
setTimeout(function() {
$("#jquery_jplayer_1").jPlayer("play", 0);
}, $('#timeout').val()*1000);
}
}
},
});
}
also if there are any options for preload all song before play, please guide me this is very important for me
thanks
Behind the scenes their is only one audio source even for playlist. jPlayer & jPlaylist are just wrappers.
This means that you can't load the next song before the current ends because that would require changing the audio source which would change the song.
Their is no built in way to do this. Maybe their is a way such as having another hidden jPlayer on the page and load the next song and somehow copying the data over without having to load but I am not sure and you probably shouldn't even have to do this.
3-4 seconds to load seems weird though, it should only load the metadata as default and in the below example for a 5 min+ song it's 46KB...
Maybe their is something wrong with your .mp3, .ogg urls. Can you post them?
This loads instantly for example:
http://jsfiddle.net/Ls8p90y9/175/
$("#jquery_jplayer_1").jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
title: "Bubble",
mp3: "http://www.jplayer.org/audio/mp3/Miaow-01-Tempered-song.mp3"
});
},
timeupdate: function(event) {
$("#jp_container_1 .jp-ball").css("left",event.jPlayer.status.currentPercentAbsolute + "%");
},
supplied: "mp3",
});
Try messing with the preload option:
preload
String : (Default: "metadata") : Valid values are "none", "metadata" and "auto", which matches the HTML5 draft standard. Use "auto" to preload the file.
Preload is a hint to the user agent, not a command. Some browsers ignore this option.

Minimalistic play() and pause() audio solution

I found a little code snippet within another question, playing an mp3 just with jquery play() and pause():
<a href="#" rel="http://www.uscis.gov/files/nativedocuments/Track%2093.mp3"
class="play">Play</a>
<div class="pause">Stop</div>
<script>
$(document).ready(function() {
var audioElement = document.createElement('audio');
var source = $('.play').attr('rel');
audioElement.setAttribute('src', source);
//audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load()
$.get();
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
$('.play').click(function() {
audioElement.play();
});
$('.pause').click(function() {
audioElement.pause();
});
});
I get the audio source from the rel attribute of the "play"-link. Now I would like to add more audio links and make the source relative to their rel attributes.
I tried
var source = $(this).attr('rel');
and also .find() and .each(), but nothing worked so far. I've set up a jsfiddle with two audio links, where only the first audio file will be played. (The fiddle links to an external script, which the client uses on his site, where only jquery 1.4.3 is loaded, but I guess it's possible anyway. I just don't want to use an audio player plugin, I aim for a minimalistic solution.)
Any help would be highly appreciated!
You can update your script to create one audio tag per container:
$(document).ready(function () {
// For each container div
$(".container").each(function() {
// Create the HTML5 <audio> tag
var audioElement = document.createElement('audio');
// Find the play/pause buttons
var $play = $(this).find(".play");
var $pause = $(this).find(".pause");
// Load the source from the play button
var source = $play.attr('rel');
audioElement.setAttribute('src', source);
$.get();
// Play the sound when loaded
audioElement.addEventListener("load", function () {
audioElement.play();
}, true);
// When the user clicks on the play button, play the audio
$play.click(function () {
audioElement.play();
});
// When the user clicks on the pause button, pause it
$pause.click(function () {
audioElement.pause();
});
});
});
And updated Fiddle: http://jsfiddle.net/sY7UT/

Categories