I'm building audio player with jQuery. And I managed to do almost everything that I wanted, but I can not make song to repeat when I click on repeat button. It should repeat if I click on repeat button and if it is enabled, when I click again to disable it.
I init audio with
music = new Audio()
I tried to use some thing like:
$('.rep').on('click', function(){
music.prop('loop');
})
but I can not get it work.
any advice, comment or tutorial would be helpful because I am looking to learn, not to copy/paste.
Thanks
U can add eventListener like this.. :
$('.rep').click(function(){
myAudio.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
});
or just edit an attr loop like this CodePen :
myAudio = document.getElementById("myAudio");
$('.rep').click(function(){
if(myAudio.loop != true){
myAudio.loop = true;
myAudio.play();
} else {
myAudio.loop = false;
myAudio.currentTime = 0;
myAudio.pause();
}
});
Hope it helps.
Related
I have created a site with image thumbnails of people I have photographed. When a visitor clicks on one of the thumbnails the full image is revealed using jQuery, and an audio introduction plays. I have a different audio introduction for each thumbnail/image combination - 15 at present with more being added daily.
I would like to ensure that if a visitor clicks on another thumbnail before the previous audio file has completed, that the previous audio file is stopped/paused to allow the new audio file to be played - thereby ensuring two or more tracks do not play simultaneously.
I am currently using the following snippet of code, wrapped in an anonymous function, to play each audio file individually when the appropriate thumbnail is clicked - so this snippet is duplicated for each audio file, but don't know how to ensure they do not play over one another.
$(".bridget-strevens").click(function(){
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused){
audio.play();
} else {
audio.pause();
}
});
Any help you could give me would be very grateful, as I am just starting to learn jQuery, and don't have the knowledge to come up with a workable solution.
Thanks in advance for your help!
Add a .audio class to all your audio elements and loop through all of them when an audio is clicked.
$(".bridget-strevens").click(function () {
$('.audio').each(function (index, value) {
if (!value.paused) {
value.pause();
}
});
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused) {
audio.play();
} else {
audio.pause();
}
});
If that seems too heavy for you then simply add the audio element in a global variable such as:
var currentAudio;
Then when a new audio is clicked, simply pause that one, play the new one and update the currentAudio variable with the new element currently being played.
var currentAudio = null;
$(".bridget-strevens").click(function () {
if(currentAudio != null && !currentAudio.paused){
currentAudio.pause();
}
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused) {
audio.play();
currentAudio = audio;
} else {
audio.pause();
}
});
Update:
Thanks for the prompt responses! Grimbode, I've tried what you
suggest, and that seems to work. However is there the ability to stop
and reset rather than just pause - so if they clicked on 1 then [2]
before 1 finished, then clicked 1 again, that 1 would start from
the beginning again rather than the point at which it was paused? And
is there any way of check the state 'globally', and then add code for
each individual audio file - just to keep the amount of code and
duplication down? Thanks again!! –
Yes. Play audio and restart it onclick explains in detail how to do this. The final result would look something like this:
var currentAudio = null;
$(".bridget-strevens").click(function () {
if(currentAudio != null && !currentAudio.paused && currentAudio != this){
currentAudio.pause();
//Here we reset the audio and put it back to 0.
currentAudio.currentTime = 0;
}
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused) {
audio.play();
currentAudio = audio;
} else {
audio.pause();
}
});
You can't really optimize the code much more. You're going to have apply the click event on every audio element. You're going to have to keep the current playing audio element memorized so you don't have to loop through all the audio files.
If you really want to take this further you could create a library to handle everything. Here is an example:
(function(){
var _ = function(o){
if(!(this instanceof _)){
return new _(o);
}
if(typeof o === 'undefined'){
o = {};
}
//here you set attributes
this.targets = o.targets || {};
this.current = o.current || null;
};
//create fn shortcut
_.fn = _.prototype = {
init: function(){}
}
//Here you create your methods
_.fn.load = function(){
//here you load all the files in your this.targets.. meaning you load the source
//OR you add the click events on them.
//returning this for chainability
return this
};
//exporting
window._ = _;
})();
//here is how you use it
_({
targets: $('.audio')
}).load();
I am making a music player by SoundCloud. It has a "Play/Pause" Button and a play list. By default the "Play/Pause" Button plays the first song of the play list. but if a song in the play list is played so it will be the current song and "Play/Pause" Button works based on that. My problem is that when I select a song, it starts playing but the previous song does not stop. unless I press "Play/Pause" Button before clicking on another song.
Here is the code:
var currentTrack = $("ul li").first().attr('id');
Finds the id val of the clicked item so this id will be song code to play.
$(document).ready(function(){
$("ul").on('click','li',function(){
currentTrack = this.id;
console.log(currentTrack);
streamTrack(currentTrack);
});
});
If the current song is alrealy playing the pressing button pause it, if not play it (toggle). Else play default item
var is_playing = false,
sound;
function player(){
if( sound ) {
if(is_playing) {
sound.pause();
is_playing = false;
} else {
sound.play();
is_playing = true;
console.log(already_played);
}
} else {
currentTrack = $("ul li").first().attr('id');
console.log(currentTrack);
streamTrack(currentTrack);
}
}
The method to play a song.
var is_playing = true;
function streamTrack(myTrack){
SC.stream("/tracks/" + myTrack, function(obj){
//obj.stopAll();
obj.play();
sound = obj;
is_playing = true;
});
}
Here is the online demo: http://jsfiddle.net/danials/wZZ4D/10/
Any idea, how to stop all songs playing and play the one is clicked?
you don't need to make a whole function for it just make sound global and pause sound or stop it sound is not null.
do like this:
var sound;
$(document).ready(function(){
$("ul").on('click','li',function(){
currentTrack = this.id;
console.log(currentTrack);
if(sound) // check if sound not null pause it
sound.pause();
streamTrack(currentTrack);
});
});
UPDATED FIDDLE
I have created a fiddle of my function here( http://jsfiddle.net/rhy5K/10/ ) . Now i want to provide the Sound "Mute/unpute" option for users. Example if i click on "a link then sound playing like Get ready,5,4,3,2,1 should be mute and vice-versa.
I am thinking like to call a to toggle_sound function on click, but i am confuse like what should i write inside the function to mute the sound.
Please provide me a logic, or a solution for my problem.
Explanation using code example:
I want to MUTE/UnMUTE this below sound playing
var playGetReady = function (done) {
var ids = ['audiosource', 'a_5', 'a_4', 'a_3', 'a_2', 'a_1'],
playNext = function () {
var id = ids.shift();
document.getElementById(id).play();
if (ids.length) {
setTimeout(playNext, 1000);
} else {
done();
}
};
playNext();
};
Warning: This JS fiddle demo may play sound on load
Try
HTML5 Video_tag for display video with audio
or
this below example along with html5 with jquery
window.my_mute = false;
$('#my_mute_button').bind('click', function(){
$('audio,video').each(function(){
if (!my_mute ) {
if( !$(this).paused ) {
$(this).data('muted',true); //Store elements muted by the button.
$(this).pause(); // or .muted=true to keep playing muted
}
} else {
if( $(this).data('muted') ) {
$(this).data('muted',false);
$(this).play(); // or .muted=false
}
}
});
my_mute = !my_mute;
});
I think you can use:
document.getElementById(id).volume = 1;
or
document.getElementById(id).volume = 0;
I am currently modifying a web app for iPad. I am trying to attach an audio soundtrack to the image slideshow. I currently have the audio files playing when the user hits the slideshow navigation controls but I can't seem to figure out how to make the audio play when the slides have automatically started.
When the nextBg() function in my main.js file moves from the current background image to the next I want it to play the next audio file in the list. The play function is: playAudio(). How do I do this?
The codes and files I am currently working with are:
function nextBg() {
if(bgRunning) return false;
clearInterval(bgTimer);
if(!$('#bgImages li.active').is(':last-child'))
$('#bgImages li.active').removeClass('active').next().addClass('active');
else
$('#bgImages li.active').removeClass('active').parent().find('li:first-child').addClass('active');
runBg();
}
function playAudio(path){
if(audioSupport){
var isPlaying = !myAudio.paused;
var canPlayMp3 = !!myAudio.canPlayType && "" != myAudio.canPlayType('audio/mpeg');
var canPlayOgg = !!myAudio.canPlayType && "" != myAudio.canPlayType('audio/ogg; codecs="vorbis"');
if(canPlayMp3)
myAudio.src = path+'.mp3';
else if(canPlayOgg)
myAudio.src = path+'.ogg';
myAudio.removeEventListener('ended', arguments.callee, false);
myAudio.addEventListener('ended', audioAddEndedListener , false);
if(autoPlay || isPlaying)
{
myAudio.play();
$('#audioControls .pause').css('display','block');
$('#audioControls .play').css('display','none');
}else{
$('#audioControls .play').css('display','block');
$('#audioControls .pause').css('display','none');
}
}
}
function audioAddEndedListener()
{
if(loop){
this.currentTime = 0;
this.play();
}else{
this.removeEventListener('ended', arguments.callee, false);
setNextAudio();
path = $('#audioList li.active').html();
playAudio(path);
myAudio.addEventListener('ended', audioAddEndedListener, false);
}
}
http://platinum.megatron.co.nz/main.js
http://platinum.megatron.co.nz/kitchen/video.html
Just call your playAudio() method inside the playBg() method after you swap the image.
I have a content slider, set to play / stop on each click.
The problem: I want it to pause on second click. Right now it won't pause. Any ideas?
See site here: http://dev.alsoknownas.ca/music/ (audio branding section on homepage).
Here's the code:
**Edited to reflect the code suggested by Lloyd below:
<audio id="player"></audio>
Here's the script:
$(document).ready(function(){
$("span.1").attr("data-src","song.mp3");
$("span.2").attr("data-src","song2.mp3");
$("span.3").attr("data-src","song3.mp3");
$("span.4").attr("data-src","song4.mp3");
$("span.5").attr("data-src","song5.mp3");
});
$("span.1,span.2,span.3,span.4,span.5").click(function () {
var player = document.getElementById("player");
player.src = this.getAttribute("data-src");
player.play();
});
for this markup:
<audio id="player"></audio>
<span class="1">one</span>
<span class="2">two</span>
use this script:
$("span.1")
.attr("data-src-mp3","song1.mp3")
.attr("data-src-ogg","song1.ogg");
$("span.2")
.attr("data-src-mp3","song2.mp3")
.attr("data-src-ogg","song2.ogg");
$("span[data-src-mp3]").click(function () {
var player = document.getElementById("player"),
$this = $(this);
if ($this.hasClass("selected")) {
if (player.paused) {
player.play();
} else {
player.pause();
}
}
else {
$("span[data-src-mp3].selected").removeClass("selected");
$this.addClass("selected");
$(player)
.empty()
.append($("<source>").attr("src", $this.attr("data-src-mp3")))
.append($("<source>").attr("src", $this.attr("data-src-ogg")))
player.play();
}
});
Live Demo: http://jsfiddle.net/75lb/8cGBx/
Try this,
Instead of doing
$('audio').bind('play','pause', function() {
Do
$('audio').bind('play pause', function(event) {
According to your code, by default audio is paused, when user clicks, it starts playing, and on next click it pauses.
Hope this works for you.