Stop audio play() when there is audio div in HTML - javascript

I have a <div onclick="startSound"> in HTML. When clicked, it triggers a sound. How can I make it stop the first sound and play another one when clicked again? Most solutions I found use the <audio> HTML tag, but since there is none, how to do it?
function startSound() {
var musicPlay=new Audio('sound.mp3');
musicPlay.play();
}

You should have a single audio element, every time you click on a certain element, instead of creating a new Audio component, change the src property of the existing Audio component.
To stop the existing Audio that is in playing state, sound.pause();sound.currentTime = 0; would help.
let myAudio = document.getElementById('myAudio');
function startSound() {
myAudio.pause();
myAudio.currentTime = 0;
myAudio.src = 'sound.mp3';
}
<audio controls id="myAudio">
<source src="anotherSound.mp3" type="audio/mpeg">
</audio>

Related

allow one audio player to play at a time

I have multiple audio players, each with a play and stop button, on one page. The only issue I have is when you click one play button, and then another, they play on top of one another. Can someone help me with the code I would need to stop whatever song is playing when another play button is clicked. Here's are my code. Thank you
function disableButton(btn) {
document.getElementById(btn.id).disabled = true;
}
function change() {
var image = document.getElementById('image');
image.src = "https://lms.testing.com/je_audio/html/button2.png"
}
#btn1 {
border: none;
padding: 0;
background: none;
}
<audio id="player">
<source src="https://lms.testing.com/els_audio/PATAudios/Q1.mp3" type="audio/mpeg">
Your browser has not support the audio element.
</audio>
<div>
<button id="btn1" onclick="document.getElementById('player').play('play'); disableButton(this)"><img src="https://lms.testing.com/je_audio/html/button1.png" width="95" height="28" alt="button" id="image" onclick="change();"></button>
</div>
Listen for the play event on all the <audio> elements.
Whenever one audio element starts playing, pause all the other ones.
// Get all <audio> elements.
const audios = document.querySelectorAll('audio');
// Pause all <audio> elements except for the one that started playing.
function pauseOtherAudios({ target }) {
for (const audio of audios) {
if (audio !== target) {
audio.pause();
}
}
}
// Listen for the 'play' event on all the <audio> elements.
for (const audio of audios) {
audio.addEventListener('play', pauseOtherAudios);
}
What you have to do is for all the elements first to stop the audio that was previously running audio and then change their images back to play, and try to play the audio for the current media button you are using. Using Class to detect all the Elements using
document.querySelectorAll('.playerButton')
this will help you find all the player button and similarly give a class like AudioFile to that audio that you are using and use the stop() function to stop the audio and then start the audio for the current button clicked using this function.
I hope this will help you, in executing the functionality you are trying to achieve.
you can use the below-given function as an example on how to stop the audio
function stopAudio(audio) {
audio.pause();
audio.currentTime = 0;
}
stopAudio(audio)

How to code a HTML5 fullscreen video player with multiple videos in loop?

I want to code an HTML5 video player without any controls. Just autoplay and loop multiple videos from a directory "my website/media" fullscreen.
The tag including "autoplay loop" and some CSS to get the video fullscreen is working fine for me, but I can't play more than one video.
Is it possible to add more videos without using any controls or visible playlists? Just playing all videos from my directory automatically in the loop?
<div class="fullscreen-video-wrap">
<video src="media/firstvideo.mp4" autoplay loop></video>
</div>
There is an "ended" event you can listen for on a element. You can do something like this to replace the src with a new video after the first one ends.
// listener function changes src
function myNewSrc() {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.src = "http://mysite/myMovie2.m4v";
myVideo.load();
myVideo.play();
}
// add a listener function to the ended event
function myAddListener(){
var myVideo = document.getElementsByTagName('video')[0];
myVideo.addEventListener('ended', myNewSrc, false);
}

Audio playback on certain link click

Here is an example code:
Link 1
Link 2
Link 3
<audio>
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
Here is a fiddle with the example code that I provided:
https://jsfiddle.net/qkuLkqao/2/
All the examples that I found use mouseover, my version would be simpler than this, playing a sound file when the user clicks on a certain link.
How can I achieve this?
I did some research on SO and Google but I couldn't find anything related (most probably I didn't searched correctly).
You can use js to manipulate the audio element...
let audio = document.getElementById("audio");
let link = document.getElementById("audioLink");
link.onclick = () => {
audio.play();
};
<a id="audioLink" href="#">Link 1</a>
Link 2
Link 3
<audio id="audio">
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
Take in to consideration that a link element is not mean to be a audio button.. you can use a button element instead..
Please try that.
document.querySelectorAll('a')[0].addEventListener('click', player, false)
function player() {
document.querySelector('audio').play()
}
This is made to play on Link 1.
You can declare use onclick on a tag and call a function to play the file.
Note. You can add the src path of the audio file as any data property in a tag and use it to play the related audio file
function playThis (el) {
if(window.audio) {
audio.pause();
}
window.audio = new Audio (el.getAttribute("data-src"));
window.audio.play();
}
Link 1
Link 2
Link 3
var links = document.getElementsByTagName('a'),
audio = document.getElementById('a-on-click'),
clickHandler = function () {
audio.play();
}
;
for (var i in links) {
links[i].addEventListener('click', clickHandler);
}
https://jsfiddle.net/qkuLkqao/14/

Stop embedded Javascript song from autplaying on Chrome?

I have the following line:
<embed src="/sounds/move.wav" autostart="0" width=0 height=0 id="move_sound" enablejavascript=true>
Which autoplays the song on Chrome regardless of any parameters I play with (autoplay, etc.).
Anyone know how to stop it from playing?
EDIT: Not the same as the above, I'm dealing only with embed tags and not video tags.
Try using an audio tag:
<audio src="/sounds/move.wav">
Your browser does not support the <code>audio</code> element.
</audio>
This tag will not autoplay the sound.
You could set src to empty string
var embed = document.getElementById("move_sound");
var audio = embed.src; // save `src`
embed.src = "";
Not really sure but maybe you could stop the audio from playing. with a function you call everytime you switch the src?
http://www.w3schools.com/tags/av_prop_currenttime.asp
Like this?
function start(){
var embed = document.getElementById("move_sound");
//load the video etc.
embed.currentTime = 0;
embed.pause();
}
function playPause() {
if (embed.paused)
embed.play();
else
embed.pause();
}

Loading Audio Element After Dynamically Changing the Source

I have a couple of audio elements that appear in the body of my page. They look like this.
<audio id="sound1" preload="auto">
<source id="sound1source" src="../../Content/Audio/gau.mp3">
//add .ogg here later
</audio>
<audio id="sound2" preload="auto">
<source id="sound2source" src="../../Content/Audio/mah.mp3">
//add .ogg here later
</audio>
The audio plays when a user mouses over certain divs. Here's the code that triggers it.
var audio = $("#sound1")[0];
$("#ChoiceA").mouseenter(function () {
audio.play();
});
var audio2 = $("#sound2")[0];
$("#ChoiceB").mouseenter(function () {
audio2.play();
});
Everything above works fine. My problem occurs when I attempt to dynamically change the source element after making an ajax call. Here's my javascript that accomplishes that.
var src1 = "../../Content/Audio/" + data.nouns[0].Audio1 + ".mp3";
var src2 = "../../Content/Audio/" + data.nouns[1].Audio1 + ".mp3";
$("#sound1source").attr("src", src1);
$("#sound2source").attr("src", src2);
When I inspect the page after triggering the ajax call to change the source path for the audio elements, I see that the source is updated. No problem there. The problem is that the audio that the new paths point to does not play.
After hunting around I found this note on w3.org "Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, either just use the src attribute on the media element directly, or call the load() method on the media element after manipulating the source elements."
The comment on w3.org seems to be related so I tried calling $('#sound1').load() and also $('#sound1source').load(). Neither solved my problem.
Can someone tell me what I've done wrong? If I need to cause the audio element to load again after dynamically changing the src, how do I do that?
-------------UPDATE-------------
Based on Swatkins suggestion I created the following function to create the audio tag when the user mouses over the target div. Unfortunately this has not solved the problem either.
function attachAudio1(src) {
$('#audio1').remove();
var audio = $('<audio>');
audio.attr("src", src);
audio.attr("id", "audio1");
audio.appendTo('body');
attachPlayAction();
};
function attachPlayAction() {
var audio = $("#audio1")[0];
$('#ChoiceA').live('mouseenter', function () {
audio.play();
});
};
You should call load like this:
var audio = $("#sound1")[0];
$("#ChoiceA").mouseenter(function () {
audio.load();
audio.play();
});
var audio2 = $("#sound2")[0];
$("#ChoiceB").mouseenter(function () {
audio.load();
audio2.play();
});
Have not tested doing it like above, but have testet this previously with a seperate function looking something like this:
<audio id="sound1" preload="auto" src="../../Content/Audio/gau.mp3">
function changeAudio(){
audio = document.getElementById("sound1");
audio.src = "../../Content/Audio/" + data.nouns[0].Audio1 + ".mp3";
audio.load();
audio.play();
}
$("#ChoiceA").mouseenter(function () {
changeAudio();
});
and that worked fine for me?
EDIT: Adding a fiddle, maybe that will help you figure this out?
http://jsfiddle.net/Z3VrV/
This is tricky. I would try replacing the whole <audio> element instead of just changing its source. This way, the new audio element hasn't been added to the page, so it will be forced to load the file.
load() followed by play() right away leads to trouble. Trying listening for the canplay event before attempting to play the audio as suggested in https://stackoverflow.com/a/8705478/1374208

Categories