I have this code that randomizes and play a song from a list of them:
var sounds = [
"sounds/royksopp.mp3",
"sounds/9thwonder.mp3",
"sounds/thisbeat.mp3",
"sounds/mosdef.mp3",
"sounds/bewater.mp3",
"sounds/boutdre.mp3",
"sounds/masterflash.mp3",
"sounds/2ep.mp3",
"sounds/drewestcoast.mp3",
"sounds/poetry.mp3",
"sounds/mfdoom.mp3",
"sounds/dreams.mp3",
"sounds/oizo.mp3", ];
function StartOrStop(audioFile) {
srcAudio = sounds[Math.floor(Math.random() * sounds.length)];
var audie = document.getElementById("myAudio");
audie.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
if (audie.paused == false) {
audie.pause();
} else {
audie.src = srcAudio;
audie.play();
}
}
When the song stops playing, it restarts with th same one. How can I make it so when the music ends, it will grab a new song from my list and automatically play it?
The problem is that you are simply calling this.play() in your ended event listener. Instead, you should be updating the src attribute with the random choice of song with this.src = srcAudio, similar to how you are for the initial selection:
function StartOrStop(audioFile) {
srcAudio = sounds[Math.floor(Math.random() * sounds.length)];
var audie = document.getElementById("myAudio");
audie.addEventListener('ended', function() {
this.currentTime = 0;
this.src = srcAudio;
this.play();
}, false);
if (audie.paused == false) {
audie.pause();
} else {
audie.src = srcAudio;
audie.play();
}
}
Hope this helps! :)
Related
I want you to play it as many times as I click on it.
(1 sec long audio only.)
function a() {
var elem = document.getElementById('musicplay');
var audio = document.getElementById('music');
var playing = false;
elem.addEventListener('click', function () {
if (playing) {
audio.play();
} else {
audio.play();
}
playing = !playing;
});
}
function playMusic() {
let playBtn= document.getElementById('musicplay');
let audio = document.getElementById('music');
let playing = false;
playBtn.addEventListener('click', ()=> {
if (playing) {
audio.pause();
playing = !playing;
} else {
audio.play();
playing = !playing;
}
});
}
what's wrong with this code, i have included the file but when i run it doesn't give the result i intended(customized design of video player),any one who is aware about javascript can help.......
function dofirst() {
//get values of buttons
var movie = document.getElementById("movie");
var playOrpause = document.getElementById("playOrpause");
var mute = document.getElementById("mute");
var fullscreen = document.getElementById("fullscreen");
//get values of sliders
var seekbar = document.getElementById("seekbar");
var myvolume = document.getElementById("volume");
//add the event listeners to buttons
playOrpause.addEventListener('click', playme, false);
mute.addEventListener('click', mute_me, false);
fullscreen.addEventListener('click', scree_full, false);
//add the event listener to sliders
seekbar.addEventListener('change', change_me, false);
seekbar.addEventListener('timeupdate', update_me, false);
seekbar.addEventListener('mousedown', mous_down, false);
seekbar.addEventListener('mouseup', mous_up, false);
myvolume.addEventListener('change', volume_up, false);
}
//the functions of play button
function playme() {
if (movie.paused == true) {
movie.play();
//update button status
playOrpause.innerHTML = 'pause';
else {
movie.pause();
//update button status
playOrpause.innerHTML = 'play';
}
}
}
//the functions of mute button
function mute_me() {
if (movie.muted == false) {
movie.muted = true;
//update button status
mute.innerHTML = 'unmute';
} else {
movie.muted = false;
//update button status
mute.innerHTML = 'mute';
}
}
//the functions of fullscreen button
function scree_full() {
if (movie.requestFullscreen) {
movie.requestFullscreen();
}
//for mozilla firefox browser
else if (movie.mozRequestFullscreen) {
movie.mozRequestFullscreen();
}
//for google chrome browsers
else if (movie.webkitRequestFullscreen) {
movie.webkitRequestFullscreen();
}
}
//the functions for seekbar
function change_me() {
//calculate current time of the video
var time = movie.duration * (seekbar.value / 100);
//update the current time of the video
movie.currentTime = time;
}
//update the seekbar when the video plays
function update_me() {
var size = movie.currentTime * (100 / movie.duration);
//update the size of the seekbar
seekbar.value = size;
}
//pause the video when the seekbar is dragged
function mous_down() {
movie.pause();
}
//play the video when the seekbar is dropped
function mous_up() {
movie.play();
}
//the function for the volume bar
function volume_up() {
movie.volume = myvolume.value;
}
window.addEventListener("load", dofirst, false);
Make sure that there are no syntax errors in your code....For instance, you seem to be using 'mous_up()' instead of 'mouse_up()'. From my own experience, javascript code doesn't run when there are any syntax errors.
I'm trying to add an event handler for an audio Javascript plugin using the SoundManager2. This is the function that plays a song and wait for the end of the song to execute the function again:
function songPlay (newSrc) {
htmlSound.src = newSrc;
htmlSound.load();
thisPlayer.find( ".total-position-scrubber" ).bind( "slide", function(event, ui) {
htmlSound.currentTime = ui.value;
});
var currentArtist = currentRow.find(".total-artist").text();
var currentTitle = currentRow.find(".total-title").text();
thisPlayer.find(".total-playing-artist").html(currentArtist);
thisPlayer.find(".total-playing-title").html(currentTitle);
htmlSound.addEventListener("timeupdate", function() {
var newVolume = thisPlayer.find( ".total-volume-slider" ).slider("option", "value");
htmlSound.volume = newVolume;
var duration = htmlSound.duration * 1000;
var durationTime = convertMilliseconds(duration, "mm:ss");
thisPlayer.find(".total-song-duration").html(durationTime.clock );
var position = htmlSound.currentTime * 1000;
var positionTime = convertMilliseconds(position, "mm:ss");
thisPlayer.find(".total-song-position").html(positionTime.clock );
thisPlayer.find( ".total-position-scrubber" ).slider("option", "max", duration/1000);
thisPlayer.find( ".total-position-scrubber" ).slider("option", "value", position/1000);
});
htmlSound.addEventListener("ended", function() {
// Find next checked song
currentRow = currentRow.nextAll(".can-play:first");
// If checked song exists after current song, load it
if(currentRow.length > 0)
{
var newSrc = currentRow.find("[src]").attr("src");
songPlay(newSrc);
}
else
{
// If no checked song exists after current song, load the first checked song in playlist
if(thisPlayer.find(".can-play").length > 0)
{
currentRow = thisPlayer.find(".can-play:first");
var newSrc = currentRow.find("[src]").attr("src");
songPlay(newSrc);
}
// Change pause button to play button
else
{
thisPlayer.find(".total-play").removeClass("total-pause");
}
}
// If song is playing while next button is clicked play next song
if(thisPlayer.find(".total-pause").length > 0)
{
htmlSound.play();
}
});
thisPlayer.find(".total-row .total-not-playing").removeClass("total-playing");
currentRow.find(".total-not-playing").addClass("total-playing");
}
The only problem is that the "ended" event is triggered more than once every time that a song finishes. After the "ended" event, the function is executed, and then the songPlay() function is executed again (this is the expected behavior), but then, the "ended" event is triggered again, before the song is finished, while it should wait for the end of the song. Any idea of the cause of that behavior?
The newSrc variable has always the right value.
This is the "ended" event definition in SoundManager2:
_html5_events = {
// HTML5 event-name-to-handler map
...
ended: _html5_event(function() {
var t = this._t;
_s._wD(_h5+'ended: '+t.sID);
t._onfinish();
}),
...
}
Edit:
Surprisingly, it worked just replacing the anonymous function with a declared function like this:
function eventListenerFunction() {
// Find next checked song
currentRow = currentRow.nextAll(".can-play:first");
// If checked song exists after current song, load it
if(currentRow.length > 0)
{
var newSrc = currentRow.find("[src]").attr("src");
songPlay(newSrc);
}
else
{
// If no checked song exists after current song, load the first checked song in playlist
if(thisPlayer.find(".can-play").length > 0)
{
currentRow = thisPlayer.find(".can-play:first");
var newSrc = currentRow.find("[src]").attr("src");
songPlay(newSrc);
}
// Change pause button to play button
else
{
thisPlayer.find(".total-play").removeClass("total-pause");
}
}
// If song is playing while next button is clicked play next song
if(thisPlayer.find(".total-pause").length > 0)
{
htmlSound.play();
}
});
function songPlay (newSrc) {
htmlSound.src = newSrc;
htmlSound.load();
thisPlayer.find( ".total-position-scrubber" ).bind( "slide", function(event, ui) {
htmlSound.currentTime = ui.value;
});
var currentArtist = currentRow.find(".total-artist").text();
var currentTitle = currentRow.find(".total-title").text();
thisPlayer.find(".total-playing-artist").html(currentArtist);
thisPlayer.find(".total-playing-title").html(currentTitle);
htmlSound.addEventListener("timeupdate", function() {
var newVolume = thisPlayer.find( ".total-volume-slider" ).slider("option", "value");
htmlSound.volume = newVolume;
var duration = htmlSound.duration * 1000;
var durationTime = convertMilliseconds(duration, "mm:ss");
thisPlayer.find(".total-song-duration").html(durationTime.clock );
var position = htmlSound.currentTime * 1000;
var positionTime = convertMilliseconds(position, "mm:ss");
thisPlayer.find(".total-song-position").html(positionTime.clock );
thisPlayer.find( ".total-position-scrubber" ).slider("option", "max", duration/1000);
thisPlayer.find( ".total-position-scrubber" ).slider("option", "value", position/1000);
});
htmlSound.addEventListener("ended", eventListenerFunction)
thisPlayer.find(".total-row .total-not-playing").removeClass("total-playing");
currentRow.find(".total-not-playing").addClass("total-playing");
}
However, I guess I should use $('body').off("ended") after the triggered function to remove the event listener, as #Fallenreaper has suggested.
you call songplay inside of a listener, which applies it another time.... and another time and another time.
recursion.
>_>
i try to play sound with the below code, but it does not play sound, so i feel sad and finally felt to ask here for your help.
Script
$(function() {
$('#btn_start').on('click', function(event){
event.preventDefault();
play_sound('mp3');
return false;
});
//------------------------
function play_sound(sound)
{
// This next line will get the audio element
// that is adjacent to the link that was clicked.
var song = $(this).next('audio').get(0);
if (song.paused)
song.play();
else
song.pause();
}
});
I suggest you to create a little class like this :
The duration cannot be get in Javascript (actually not implemented on every browsers, you must set this value for each "songs")
Fiddle: http://jsfiddle.net/XYevE/4/
(nota: this is just an example, developped very fast...:))
HTML:
PLAY
<div id="timer"><span>click play</span></div>
<div id="ms">
Before callback:
<span id="mins"></span>:
<span id="secs"></span>
</div>
<audio id="audiosource">
<source src="http://www.cumfortitudine.com/vvdemo/assets/js/actions/vquery.vdemo/scenes/assets/sound/hans-zimmer-injection.mp3" type="audio/mpeg" />
</audio>
Javascript:
function myApp() {
this.paused = false;
this.paused = true // set pause to true (stop)
this.isactive = false; // countdown is active
this.duration = 0; // set duration to 0 (get via audio DOM)
return this.observer(); // call and return the "observer" method of the "myApp" class
}
myApp.prototype.observer = function() { // observer method
var self = this; // set this to self (this is the current instance of this class)
$('#btn_start').on('click', function(event){ // where an user click on "btn_start"
event.preventDefault();
self.play('mp3'); // call the play method and store the state in a public var
self.countdown(self.onEnd); //parameter is the callback when the audio is finished
self.isactive = true;
});
return this; // return this instance
};
myApp.prototype.play = function() { // play method
var song = document.getElementById('audiosource');
this.duration = song.duration;
if (this.paused === true)
{
$('#btn_start').html('PAUSE');
console.log('set play song');
song.play();
this.paused = false;
}
else
{
$('#btn_start').html('PLAY');
console.log('set pause song');
song.pause();
this.paused = true;
}
return this;
};
myApp.prototype.countdown = function(duration, callback) { // countdown method
var self = this, // class instance
countdown = null, // countdown
ctx = null; // setIntervall clearer
timer = this.duration * 1000; // timer in milliseconds
if (this.isactive === true) // if this method yet called
{
return false;
}
countdown = function() {
if (timer <= 0)
{
self.isactive = false; // reset
clearInterval(ctx);
callback.call(this);
return false;
}
if (self.paused === false) // if not in pause
{
timer -= 250;
var mins = parseInt((timer / 1000) / 60);
var secs = parseInt((timer / 1000) - mins * 60);
$('#mins').html(mins);
$('#secs').html(secs);
$('#timer > span').html(timer.toFixed(2));
}
};
ctx = setInterval(countdown, 250);
};
myApp.prototype.onEnd = function() {
// when the audio is finish..
alert ('end of the song');
};
;$(function() {
new myApp();
});
I made a quick audio player that has multiple instances. When you click to play, the playing var is set to true. If one would click on a different instance of .playAudio, I'm trying to set the lastPlayed instance to false.
I have a portion where I commented out the part I can't figure out.
JQUERY:
var lastPlay
var lastSelected
$('.playAudio').each(function(){
var audio = $(this).find('audio').get(0);
var playing = false
$(this).hover(function() {
if (playing) {
$(this).css({backgroundPosition: '-60px -60px'})
} else {
$(this).css({backgroundPosition: '0px -60px'})
}
},function() {
if (playing) {
$(this).css({backgroundPosition: '-60px 0'})
} else {
$(this).css({backgroundPosition: ''})
}
});
$(this).click(function(){
if (playing) {
playing = false
$(this).css({backgroundPosition: '0 60px'})
audio.currentTime = 0
audio.pause()
} else {
if (lastPlay) {
//** I'm trying to change the lastSelected's "playing" to false
lastPlay.pause()
}
playing = true
$(this).css({backgroundPosition: '-60px -60px'})
audio.play()
lastPlay = audio
lastSelected = $(this)
}
})
})
Here's one way to do it:
var lastPlay,
lastSelected,
Audios = [];
$('.playAudio').each(function(i){
var Audio = {};
Audios[i] = Audio;
Audio.audio = $(this).find('audio').get(0);
Audio.playing = false;
$(this).hover(function() {
if (Audio.playing) {
$(this).css({backgroundPosition: '-60px -60px'});
} else {
$(this).css({backgroundPosition: '0px -60px'});
}
},function() {
if (Audio.playing) {
$(this).css({backgroundPosition: '-60px 0'});
} else {
$(this).css({backgroundPosition: ''});
}
});
$(this).click(function(){
if (Audio.playing) {
Audio.playing = false;
$(this).css({backgroundPosition: '0 60px'});
Audio.audio.currentTime = 0;
Audio.audio.pause();
} else {
if (lastPlay && Audios[lastPlay]) {
Audios[lastPlay].audio.pause();
Audios[lastPlay].playing = false;
}
Audio.playing = true;
$(this).css({backgroundPosition: '-60px -60px'});
Audio.audio.play();
lastPlay = i;
lastSelected = $(this);
}
});
});
I've changed your script in a few ways:
I'm capturing the first parameter that jQuery passes into .each and using it as Unique Identifier between Audio Players
For each audio player the <audio> element, and it's playing state are being kept in the local Object Audio
I store a reference to each Audio Object as an array element in the global array Audios; using the unique identifier as the index
lastPlay now only holds the unique identifier of the last played audio element; I use it to access the appropriate Object in the Audios array, and set the relavent playing when necessary.