Javascript play sound on click, second button click stop first sound - javascript

I have this code that on button press it plays a sound, What I want is when one sound is playing from first click if you click another button before its over it stops the first one and plays the next one you clicked on.
Any ideas would be great.
<!DOCTYPE html>
<head>
<title>Sounds</title>
</head>
<body>
<audio id="sound1" src="sounds/sound1.mp3"></audio>
<audio id="sound2" src="sounds/sound2.mp3"></audio>
<button onclick="document.getElementById('sound1').play()">Sound 1</button><br />
<button onclick="document.getElementById('sound2').play()">Sound 2</button><br />
</body>
</html>
Thanks in advance.

Try something like that:
<audio id="sound1" src="sounds/sound1.mp3"></audio>
<audio id="sound2" src="sounds/sound2.mp3"></audio>
<button onclick="playSound1()">Sound 1</button><br />
<button onclick="playSound2()">Sound 2</button><br />
<script type="text/javascript">
var audio1 = document.getElementById('sound1');
var audio2 = document.getElementById('sound2');
function playSound1(){
if (audio1.paused !== true){
audio1.pause();
audio2.play();
}
else{
audio2.play();
}
}
function playSound2(){
if (audio2.paused !== true){
audio2.pause();
audio1.play();
}
else{
audio1.play();
}
}
</script>
Though I would advice you use the addEventListener method on the button tag rather than the onclick attribute as it is more maintainable.
Thanks

Put the id of the corresponding audio into a data-target attribute on a button. On load, get the buttons and assign a click handler that
Reloads the current Audio, sets the current Audio element to the button's target, and plays the current Audio

Related

How to toggle multiple play/pause buttons with different srcs

I'm facing some issues with my play/pause buttons. In ym HTMl I have multiple buttons with different sources:
<div>
<button class="button-53" id="button">Play</button>
</div>
<audio id="player">
<source src='audio/mixdown.mp3' type='audio/mpeg'/>
</audio>
<div>
<button class="button-53" id="button">Play</button>
</div>
<audio id="player">
<source src='audio/mixdown2.mp3' type='audio/mpeg'/>
</audio>
This is my Javascript:
var buttons = document.getElementById("button");
var music = document.getElementById("player");
for (const buttons of button) {
buttons.addEventListener("click", function(){
if(music.paused){
music.play();
buttons.innerHTML = "Pause";
} else {
music.pause();
buttons.innerHTML = "Play";
}
});
}
But when I play music from the first button and then pause it, go over to the next button and toggle the button, the sound keeps playing from that point where I stopped it instead of playing the sound from the written source.
Anyone here that could help me?
Id attributes in HTML should be unique. The document.getElementById returns a single element (if found).
One solution to fixing your problem is to give each pair of button/audio elements different ids, for example:
<div>
<button class="button-53" id="button1">Play</button>
</div>
<audio id="player1">
<source src='audio/mixdown.mp3' type='audio/mpeg'/>
</audio>
<div>
<button class="button-53" id="button2">Play</button>
</div>
<audio id="player2">
<source src='audio/mixdown2.mp3' type='audio/mpeg'/>
</audio>
and then add event listeners for each pair:
function addListeners(buttonElement, audioElement) {
// ...add implementation
}
addListeners(
document.getElementById("button1"),
document.getElementById("player1")
);
addListeners(
document.getElementById("button2"),
document.getElementById("player2")
);

How to stop playing audio with javascript and jquery

I'm new to JQuery and JavaScript and I have this situation:
<button style="background-color: #dfe52d;border:4px solid #dfe52d"
class="button" type="button" >Play Me!</button>
<audio class="audio" src="audio.mp3" type="audio/mpeg"></audio>
There are many buttons on my page, all with the same structure. For each button I want play a different sound:
$(document).ready(function(){
$("button").click(function(){
var isPlaying=false
var audio = $(this).next().attr("src");
var music = new Audio(audio);
if(isPlaying) {music.pause()}
else{music.play();$(this).text("Stop Me")}
});
});
When a button is clicked, the sound plays and the button text changes to "stop me". How can I write the code to stop the audio? Also, if the user presses another button the current song must stop. How can I achieve this? Thanks.
Try setting the isPlaying outside of the button click event and querying that so you know the state when you press the button. At the moment you set isPlaying to false every time you click.
var isPlaying=false
$(document).ready(function(){
$("button").on("click", function(){
var audio = $(this).next().attr("src");
var music = new Audio(audio);
if (!isPlaying) {
// Not playing, let's play
isPlaying = true;
music.play();
$(this).text("Stop Me")
} else {
// Stop the music
isPlaying = true;
music.pause();
$(this).text("Play");
};
});
});
Here's the cleanest solution. Most of the functionality you're looking for is already built into the JavaScript for audio tags.
<script>
$(document).ready(function(){
$("button").click(function(){
var audio = $(".audio")[0];
if (audio.paused) {
audio.play();
$(this).html("Stop me!");
} else {
audio.pause();
$(this).html("Play me!");
}
});
});
</script>
hi thanks all of you for the quick response.
unfortunately this two solution didnt work out, so i opted for this:
<button style="background-color: #dfe52d;border:4px solid #dfe52d;" class="button" onclick="document.getElementById('audio1').play()" type="button" >Play Me!</button>
<button style="background-color: #dfe52d;border:4px solid #dfe52d;" class="button" onclick="document.getElementById('audio1').pause()" type="button" >Stop Me!</button>
<button style="background-color: #dfe52d;border:4px solid #dfe52d;" class="button" onclick="document.getElementById('audio1').currentTime=0.0" type="button" >Restart Me!</button>
<audio class="audio" id="audio1" src="audio.mp3" type="audio/mpeg"></audio>
Now works fine except one problem, i need a function to stop the current sound when another button is pressed. Is it a simple task in your opinion? Thank you

Changing Videos on Button Click (multiple Buttons)

I am trying to change a video with various other options, the idea is the user clicks the button of the video they want to watch and it replaces the current one in the video area.
I want to do this with a simple java script as more videos will be added later on so i don't want to include a whole bunch of links in a java script. I was hoping to use a this function of some sort but i assume my knowledge in this area isn't up to speed yet.
Can anyone help solve this please?
HTML
<button onClick="changevid(vid/Video1.mp4)">Video 1</button>
<button onClick="changevid(vid/Video2.mp4)">video 2</button>
<button onClick="changevid(vid/Video3.mp4)">Video 3</button>
<button onClick="changevid(vid/Video4.mp4)">video 2</button>
<video controls>
<source src="vid/Video1.mp4" id="change" type="video/mp4"></source>
</video>
JS
<script language="javascript" type="text/javascript">
function changevid(){
document.getElementById('change').src = buttonlink;
}
</script>
Thanks in advance,
Phil
Multiple videos with multiple buttons use below simply
Html
<video id="vid" controls autoplay style="width:75%">
<source id="src" src="video2.mp4" type="video/mp4">
</video><br/><br/>
<button id="change1">video1</button>
<button id="change2">video2</button>
<button id="change3">video3</button>
</div>
JavaScript
<script>
const v = document.getElementById("vid");
const s = document.getElementById("src");
function changeVideo1() {
s.src = 'video1.mp4';
v.load();
v.play();
}
function changeVideo2() {
s.src = 'video2.mp4';
v.load();
v.play();
}
function changeVideo3() {
s.src = 'video3.mp4';
v.load();
v.play();
}
document.getElementById("change1").onclick=changeVideo1;
document.getElementById("change2").onclick=changeVideo2;
document.getElementById("change3").onclick=changeVideo3;
</script>
Pass url as string
<button onClick="changevid('vid/Video1.mp4')">Video 1</button>
function must receive the argument
function changevid(buttonLink) {
id attribute should be on the video tag
<video controls id="change">
<source src="vid/Video1.mp4" type="video/mp4"></source>
</video>
http://jsfiddle.net/3dp8khg3/
There are many ways that I can think of to do this. Your method is valid but just needs some adjustment to work.
To get your method to work firstly you need to change your changeVid method to take a parameter otherwise you will not be able to pass the video link/id to the method.
So change
function changevid(){
to
function changevid(buttonLink){
and then the line;
document.getElementById('change').src = buttonLink;
will actually work as buttonLink now has a value.
One final change is to wrap your video locations in quotes ' ' in order for them to pass through to the changevid method as a string.
so
<button onClick="changevid(vid/Video1.mp4)">Video 1</button>
becomes
<button onClick="changevid('vid/Video1.mp4')">Video 1</button>

Changing the song of the html5 audio player

I want to use javascript to change the src like so:
<script>
function myFunctionP1() {
mysong = "http://www.afinerweb.com/music/bensound-slowmotion.1.mp3";
}
function myFunctionP2() {
mysong = "http://www.afinerweb.com/music/bensound-slowmotion.2.mp3";
}
</script>
and have some buttons to control music selection like so:
<button type="button" onclick="myFunctionP1()">set player to Song1</button>
<button type="button" onclick="myFunctionP2()">set player to Song2</button>
but that does not seem to work. Can someone please point out the correct solution?
You need to change the src attribute of the audio, so you can assign an id to the audio element and use that to access it and set the src value in teh click handler
function myFunctionP1() {
document.getElementById('mysong').src = "http://www.afinerweb.com/music/bensound-slowmotion.1.mp3";
}
function myFunctionP2() {
document.getElementById('mysong').src = "http://www.afinerweb.com/music/bensound-slowmotion.2.mp3";
}
<audio id="mysong" src=mysong controls preload="metadata">
<p>Your browser doesn't support html5 audio.</p>
</audio>
<button type="button" onclick="myFunctionP1()">set player to Song1</button>
<button type="button" onclick="myFunctionP2()">set player to Song2</button>

Javascript/html audio problems

I'm having some problems in my code. To begin, I would like for a song to play after a song I am playing ends (with the audio tag).
<audio id="batmansong1">
<source src="Songs/nanananabatman.m4a">
</audio>
<button id="play" onclick="document.getElementById('batmansong1').play()"><img src="Buttons/play.jpg" height="40" width="40"></button>
<button id="pause" onclick="document.getElementById('batmansong1').pause()"><img src="Buttons/pause.jpg" height="40" width="40"></button>
As you can see, the buttons will play or pause the first audio clip. However, I want them to also pause and play the second audio clip when it starts playing.
Your buttons will still be working when doing this. You can add an eventlistener that checks if te <audio> element ended playing. Then you just set the next source and start playing again. (BTW you'd better not use inline javacript and old html styling (I mean width="40" and such, just use CSS))
all the code below is in this jsfiddle
JS:
player = document.getElementById('batmansong1');
player.addEventListener('ended', function () {
if (player.src == 'link/to/your/next/file.m4a') return; //check if we have already set the new src, as this function is called EVERY TIME your audio file ends.
player.src = 'link/to/your/next/file.m4a';
player.play();
});
document.getElementById('pause').addEventListener('click', function () {
document.getElementById('batmansong1').pause();
});
document.getElementById('play').addEventListener('click', function () {
document.getElementById('batmansong1').play();
});
HTML:
<audio id="batmansong1" src="Songs/nanananabatman.m4a"></audio>
<button id="play">
<img src="Buttons/play.jpg" />
</button>
<button id="pause">
<img src="Buttons/pause.jpg" />
</button>
CSS:
img {
width:40px;
height:40px;
}
If you want to know anything else, feel free to ask!
//It should work for html 5 surpport browsers
function htmlfiveMedia(){
document.getElementById('player').play();
}
//in your html
<audio id="player" src="../jizadmin/sounds/new_message.wav"></audio>
OR
IF THE BROWSER DOES NOT SUPPORT AUDIO TAG TRY THIS BELOW
//This function is going to play sound
function explorerMedia()
{
$('embed').remove();
$("<embed src='../jizadmin/sounds/new_message.wav' autostart='true' hidden='true' height='1' width='1'>").insertAfter('hr');
}
//add an <hr> below your page
Hope this would help

Categories

Resources