Play one HTML audio element at a time - javascript

I have many audio elements on a single page and I want to play just one element at a time. That is if one audio element is playing and I click on play on another element, the previous audio element should pause.
I found a jQuery code from another question to do this but that uses an image as play/pause controls. I'm using the inbuilt controls='controls' attribute for the audio element instead. Is it possible to use jQuery to control the play/pause feature for the audio element in my case?
Here is my HTML code
<div>
<p class="song"><h3><strong>#1 Intro - The Oath</strong></h3><p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>
<div>
<p class="song"><h3><strong>#2 A State Of Trance Year Mix 2013</strong></h3></p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>
Here is the jQuery code
$(document).ready(function() {
var curPlaying;
$(function() {
$(".playback").click(function(e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if(song.paused){
song.play();
if(curPlaying) $("audio", "#"+curPlaying)[0].pause();
} else { song.pause(); }
curPlaying = $(this).parent()[0].id;
});
});
});
The jQuery code doesn't seem to be working for me.

$(function(){
$("audio").on("play", function() {
$("audio").not(this).each(function(index, audio) {
audio.pause();
});
});
});
See sample at JSFiddle

Vanilla JS solution
Here's a solution that doesn't require jQuery.
function onlyPlayOneIn(container) {
container.addEventListener("play", function(event) {
audio_elements = container.getElementsByTagName("audio")
for(i=0; i < audio_elements.length; i++) {
audio_element = audio_elements[i];
if (audio_element !== event.target) {
audio_element.pause();
}
}
}, true);
}
document.addEventListener("DOMContentLoaded", function() {
onlyPlayOneIn(document.body);
});
Some things to note:
Because this listens for events on a parent element, not on the audio elements themselves, they can be added or removed after the page is loaded and it will still work.
It watches for the play event in the capture phase because play events don't bubble.
More media events are described here on MDN.
Listening for "DOMContentLoaded" should work for most browers.

Little Modification to LostInComputer's Answer
In Your HTML Write:
<audio controls onplay="pauseOthers(this);" >
<source src="SourcePath">
</audio>
In Js Write:
function pauseOthers(ele) {
$("audio").not(ele).each(function (index, audio) {
audio.pause();
});
}

Assuming that your syntax for stopping and pausing tracks is correct (I don't know anything about the audio element), you should be able to do something like this:
$(".playback").click(function(e) {
// pause all other tracks
$('.audio').each(function () {
var song = this;
if (!song.paused) { song.pause(); }
});
// play the audio associated with this element
this.play();
});

<script>
function controlplay(e) {
document.querySelectorAll('.playback').forEach(item => { if(item.id != e.target.id) item.pause(); });
}
</script>
<script>
document.querySelectorAll('.').forEach(item => { item.addEventListener("play", event => { controlplay(event) })});
</script>

Angular:
<audio (play)="audioPlay($event)" controls preload="none">
<source [src]="url" type="audio/mpeg">
</audio>
audioPlay(e) {
let eAudio = this.domService.getDocument.getElementsByTagName('audio')
if (eAudio && eAudio.length > 0) {
for (var i = 0; i < eAudio.length; i++) {
if(e.target !== eAudio[i]){
eAudio[i].pause();
}
}
}
}

<script>
var nowplaying = null;
// Pause and reset playing audio before starting new selection
function pauseRunningAudio(id) {
if ( nowplaying != null && nowplaying != id) {
var x = document.getElementById(nowplaying);
x.pause();
x.load();
}
nowplaying = id;
}
</script>
<!-- id and function value must be the same -->
<audio controls onplay="pauseRunningAudio('song1')" id="song1">
<source src="Bohemian Rhapsody.mp3" type="audio/mpeg">
</audio>
<audio controls onplay="pauseRunningAudio('song2')" id="song2">
<source src="November Rain.mp3" type="audio/mpeg">
</audio>
<audio controls onplay="pauseRunningAudio('song3')" id="song3">
<source src="Smoke on the Water.mp3" type="audio/mpeg">
</audio>

Related

Audio on add to cart with raw javascript

What exactly is wrong with my selection?
<audio id="cart_add_sound" controls="" preload="auto" hidden="hidden"> <source src="img/cart_add.wav"
type="audio/wav"> </audio>
creating a function
targeting class button-4
attaching an even listener to mouse click
and play the audio with an id of cart_add_sound
// Play Audio on Add to Cart
function playAudio() {
var play = document.querySelector('.button-4')
play.addEventListener('click', function() {
document.getElementById('cart_add_sound').play();
}, true);
}
i know i could use inside html5 onclick="audio.play()" but i want to approach it this way for learning purpose.
You should initialize / execute this function, for example, after the DOM is ready:
// Play Audio on Add to Cart
function playAudio() {
var play = document.querySelector('.button-4')
play.addEventListener('click', function() {
document.getElementById('cart_add_sound').play();
}, true);
}
// DOM ready event
document.addEventListener('DOMContentLoaded', (event) => {
playAudio();
});
Have you run it somewhere?
Demo - https://codepen.io/vyspiansky/pen/BaKKdvW
i fixed it by using getElementsByClassName
and looping through all elements.
// Play Audio on Add to Cart
function playAudio() {
var plays = document.getElementsByClassName('button-4')
for (var i = 0; i < plays.length; i++) {
var play = plays[i]
play.addEventListener('click', function() {
document.getElementById('cart_add_sound').play();
}, true);
}
}

How to toggle audio play() pause() with a button click?

I have added an audio to my website, which is playing when site is opened. Now I want add play/pause button to toggle the audio.
This is how I tried it:
<audio id="myAudio" autoplay >
<source src="mp3/background-music.mp4" type='audio/mp4'>
Your user agent does not support the HTML5 Audio element.
</audio>
<a type="button" class="play-pause" title="play/pause"><i class="fa fa-pause"></i></a>
<script type="text/javascript">
$(document).ready(function() {
var playing = false;
$('a.audio-btn').click(function() {
if (playing == false) {
document.getElementById('myAudio').play();
playing = true;
$(this).text("stop sound");
} else {
document.getElementById('myAudio').pause();
playing = false;
$(this).text("restart sound");
}
});
});
</script>
But its not working for me. Can anybody tell me where I have gone wrong?
For demo purpose, i add video tag, to work with audio you can replace video to audio tag and Use
$('.play-pause')
Instead of
$('a.audio-btn')
For audio use this at the place of video tag :
<audio id="myAudio" autoplay>
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='audio/mp4'>
Your user agent does not support the HTML5 Audio element.
</audio>
$(document).ready(function () {
var playing = true;
$('.play-pause').click(function () {
if (playing == false) {
document.getElementById('myAudio').play();
playing = true;
$(this).text("Sop Sound");
} else {
document.getElementById('myAudio').pause();
playing = false;
$(this).text("Restart Sound");
}
});
});
a {
background: #000;
color: #fff;
cursor: pointer;
padding: 10px;
}
video {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="myAudio" autoplay>
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='video/mp4'>
Your user agent does not support the HTML5 Audio element.
</video>
<a type="button" class="play-pause" title="play/pause">Play / Pause</a>
Change your $('a.audio-btn') into $('a.play-pause').
What exactly is not working? Does the button not appear, does it not function?
I would suggest using something like the following:
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause()
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};

Javascript onclick video object autostart true

How can I change a property of a source element / video object.
In my case I want to change the property autostart from false to true;
html:
<video id="modul_1_video" controls preload="none">
<source id="modul_1_source" src="../video.mp4" type="video/mp4" autostart="false">
</video>
js: (I do not want to use jquery)
modul_1.onclick = function() {
console.log("click works");
document.querySelector("#modul_1_video > source").autostart = true;
}
but it does not seem to work.
why don't you just use the play function?
modul_1.onclick = function() {
console.log("click works");
var video = document.getElementById("#modul_1_video");
video.play();
}
set "autostart" attribute to true on click
document.getElementById('modul_1_source').setAttribute('autostart','true');
modul_1.onclick = function() {
console.log("click works");
document.getElementById("#modul_1_video").setAttribute("autostart","true");
}

Video Onclick function for playing a video

I have designed a video question using Html and i have removed controls for video using Jquery, so i need to have onclick functionality like when we click on the video it should be played and if am clicking again it should be paused .
Below your html code
<video id="video" width="1180" height="664" poster="put here your poster url" preload="auto">
<source src="put here your video url" type="video/mp4">
</video>
Below jquery code
var video = document.getElementById("video");
video.addEventListener("click", function(event) {
if (video.paused == true) {
video.play();
}
else{
video.pause();
}
});
You can play or pause a vide like this. This should be able to toggle:
$(document).ready(function(){
$('YOUR_VIDEO_ID_OR_CLASS').click(function(){
$(this).get(0).paused ? $(this).get(0).play() : $(this).get(0).pause();
});
});
An easy way could be like this:
$(function() {
var video = $('video')[0];
$('button').click(function() {
if( video.paused ) {
video.play();
}
else {
video.pause();
}
});
});
Fiddle Example
You can change 'button' to another element as trigger for the play/pause.
You can also change it to the video it self, if you want just to click on the video to play and pause it.
This is what you need:
<script type="text/javascript">
function vidplay() {
var video = document.getElementById("Video1");
var button = document.getElementById("play");
if (video.paused) {
video.play();
button.textContent = "||";
}
else
{
video.pause();
button.textContent = ">";
}
}
</script>

How to toggle audio play() pause() with one button or link?

I have an audio file that plays when an anchor tag is clicked. If the anchor tag is clicked again, I want the audio to pause, I just don't know enough about javascript to pull this second half off. I don't want to change the content of the anchor tag they click, I just want the audio file to start and pause whenever they click the tag.
This is what I have so far, which at least makes the sound file playable:
<audio id="audio" src="/Demo.mp3"></audio>
<a onClick="document.getElementById('audio').play()">Click here to hear.</a>
A Vanilla Javascript way to do what you required.
Note: I've noticed comments on other question with multiple upvotes for a native js approach and saw the OP has no jquery tag.
So WORKING EXAMPLE:
SOLN 1: (my initial soln using events)
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
isPlaying ? myAudio.pause() : myAudio.play();
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
<audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>
SOLN 2: (using myAudio.paused property based on dandavi's comment)
var myAudio = document.getElementById("myAudio");
function togglePlay() {
return myAudio.paused ? myAudio.play() : myAudio.pause();
};
<audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>
var audioElement= document.getElementById("audio-player");
function togglePlay() {
if (audioElement.paused) {
audioElement.play();
}
else {
audioElement.pause();
}
};
You could use jQuery to make a toggle for this.
<a id="music-button" style="cursor:pointer;">
<img src="http://i.stack.imgur.com/LT3WE.png"></a>
<audio id="playMusic" autoplay>
<source src="sound.mp3">
</audio>
<script type="text/javascript">
$('#music-button').toggle(
function () {
document.getElementById('playMusic').play();
},
function () {
document.getElementById('playMusic').pause();
}
);
</script>
the myAudio variable has to be inside the function call...It works fine
function togglePlay() {
var myAudio = document.getElementById("myAudio");
return myAudio.paused ? myAudio.play() : myAudio.pause();
};
<audio
id="myAudio" src="https://clubajax.pythonanywhere.com/media/contact/backgroundM.mp3" preload="auto">
</audio>
<input type="button" value="sound" onclick="togglePlay()" />
var Sample-Audio = document.getElementById("Sample");
function togglePlay() {
return Sample-Audio.paused ? Sample-Audio.play() : Sample-Audio.pause();
};
<audio id="Sample" preload="auto">
<source src="./sounds/rain.mp4" type="audio/mp4">
<source src="./sounds/rain.ogg" type="video/ogg">
</audio>
<a onClick="togglePlay()">Click here to hear.</a>
HTML
<audio controls autoplay class="bgsound">
<source src="audio/motivational-day-112790.mp3" type="audio/wav" />
<source src="audio/motivational-day-112790.mp3" type="audio/wav" />
<source src="audio/motivational-day-112790.mp3" type="audio/wav" />
Your browser does not support the audio element.
</audio>
Javascript
var audioClass = document.querySelector(".bgsound");
document.querySelector(".play-pause").addEventListener("click",
function () {
if (audioClass.paused) {
audioClass.play();
} else {
audioClass.pause();
}
});

Categories

Resources