multiple audio, auto stop other when current is playing with javascript - javascript

I have more than 5 audio players with audioplayer.js on a html5 page.
Does anyone has a simple script in js to pause all other players when the current player is playing ?
jQuery:
$( function(){
$("audio").audioPlayer();
});
Library
https://osvaldas.info/examples/audio-player-responsive-and-touch-friendly/audioplayer.js
I have tried as below
window.player = $('audio')[0];
$('.audioplayer-playpause').click(function () {
if (player.paused) {
player.play();
} else {
player.pause();
}
});
I have made a jsFiddle just to easeout things and below is the link:
JS Fiddle for Audio Player

Try the below code.I have tested it in JS Fiddle & it is working :) :)
Updated JSFiddle
Put this code in Javascript & remove yours.
document.addEventListener('play', function(e){
// get all <audio> tag elements in the page.
var allAudios = document.getElementsByTagName('audio');
// Iterate through all players and pause them, except for
// the one who fired the "play" event ("target")
for(var i = 0; i<allAudios.length; i++){
if(allAudios[i] != e.target){
allAudios[i].pause();
}
}
}, true);

Related

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.

Toggle audio "start/stop" with click of image

Could someone please help me add some simple functionality to this string?
Here is what I use to allow people to click on an image and play an audio file...the song plays until its over and wont stop. I would like to allow people to click it a second time to stop the song, and reset it back to the beginning:
$(document).ready(function()
{
var element = $('#starspangledbanner');
var audio = new
Audio('http://siteassets.starspangledbanner.mp3');
element.click(function(e)
{
e.preventDefault();
audio.play();
});
});
Thanks in advance.
You can follow this code. It's very easy and woks fine:
$(document).ready(function(){
var element = $('#starspangledbanner'),
audio = new Audio('http://siteassets.starspangledbanner.mp3');
element.click(function(e){
e.preventDefault();
if(audio.paused){
audio.play();
}else{
audio.pause();
audio.currentTime = 0;
}
});
});

Toggle Play/Pause Youtube Video with external button

I have a template I'm building out using fullPage js to create sliding sections. The page supports video, but scroll and gestures are disabled when users scroll with the cursor on top of the video itself. Likewise, this behavior is observed on mobile.
To work around this, I'm using an empty div overlaying the youtube iframe. This solves the scrolling behavior, but I also lack the ability to directly control the youtube player. I've tried using the youtube API and jquery to fake being able to toggle play/pause with the empty div I have on top of the youtube player, but it's not working.
http://codepen.io/lumpeter/pen/XpayeB
The primary code for youtube is:
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("player");
ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
}
function onPlayerReady(event) {
$('#video-button').click(function(event){
ytplayer.playVideo();
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
$('#video-button').click(function(event){
ytplayer.pauseVideo();
});
}
else {
$('#video-button').click(function(event){
ytplayer.playVideo();
});
}
}
Can anybody tell why this isn't working? I have event listeners looking for changes and using a boolean to detect the state of the video to toggle play/pause, but for some reason this doesn't work like I anticipated.
===============UPDATE=================
I've also tried the following:
$(document).on('click', '#pauseVideo', function(){
player = new YT.Player('myVideo')
if (event.data == player.PlayerState.PAUSED) {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*');
}
if (event.data == player.PlayerState.PLAYING) {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
}
});
However, I get the error "Uncaught ReferenceError: YT is not defined."
As fullpage.js already does part of the job by adding ?enablejsapi=1 and loading the JS script of the API for you, then you only have to do this:
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('myVideo');
}
$(document).on('click', '#pauseVideo', function(){
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
});
Reproduction online
Thanks Alvaro! Yeah I was overthinking the solution a bit with the youtube api. I just needed to use a boolean with a binary true/false statement. Super easy, should have seen it before. Again thanks for your help!
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('myVideo',{
events: { 'onStateChange': onPlayerStateChange }
});
}
var isPlaying = true;
$(document).on('click', '#pauseVideo', function(){
if ( isPlaying == true){
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
isPlaying = false;
} else {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*');
isPlaying = true;
}
});

YouTube, onPlayerReady, use for loop to get the Video ID in the array that matches the click arrow position and play

I have the following fiddle: http://jsfiddle.net/inkedraskal/cyhyjht5/3/
In the fiddle you'll see that you can play and pause individual videos by clicking on the them (play one, if you click on another it will stop that current video and play what you clicked on).
What i can't figure out is how to get the custom play button to work. I have following for loop in the fiddle, but I'm guessing on click its not matching up the placement in the array. If i'm clicking the 3rd "play" span, it should be playing the 3rd video:
function onPlayerReady(event) {
for (var i = 0; i < players.length; i++) {
// if (players[i].getVideoUrl() != temp) players[i].stopVideo();
for (var q = 0; q < ytPlayButtons.length; q++) {
playButton = document.getElementById(ytPlayButtons[q]);
playButton.addEventListener("click", function() {
console.log(playButton);
players[i].playVideo();
});
}
}
}
Hi i have edited you fiddle and remake the onPlayerReady() function:
fiddle
there the new code:
var videoCount = 1;
function onPlayerReady(event) {
$("#play-"+videoCount).on("click", function() {
console.log("play-"+videoCount);
event.target.playVideo();
});
videoCount++;
}
this is the easy way to do.
you should take the id of the video and than link it to the button in some way.
The problem with your initial code is that event.target contains a single video and the function loop all the video in page, so you don't need to write more cycle inside.
from youtube api you can use even this function to works with videos:
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
}
than ytplayer will have the same property of event.target and you have the videoID for free to use

MediaElement.js: Trigger event, if some specific audio file has ended

Referring to MediaElement.js. How to trigger an event (call a function), if some specific audio file has ended?
var myAudioFiles = ['audioFile1.wav', 'audioFile2.wav', 'audioFile3.wav'];
var myPlayer = new MediaElementPlayer('#myPlayer');
myPlayer.setSrc(myAudioFiles[0]);
myPlayer.play();
Pseudo Code:
if (hasEnded(myAudioFiles[0])) {
doSomething();
}
Please try this.
$(function(){
$('audio,video').mediaelementplayer({
success: function(player, node) {
player.addEventListener('ended', function(e){
player.src = 'media/somefile.mp4';
player.load();
player.play();
});
}
});
});
copied from here:
mediaelement.js - play another video at end of 1st video

Categories