How to stop playing audio with javascript and jquery - javascript

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

Related

Javascript play/pause toggle functionality

I am trying to add play/pause toggle functionality to a single button for an mp3 player project where the play button will turn to a "||" icon when music is playing and will revert to the play button when the music is paused by only using vanilla JavaScript. I have tried implementing an if-else statement which seems to be commonly used for this type of functionality, but the icon will only change to the "||" icon when the song is played, but will not pause and change to the play icon when clicked again. I have tried creating a separate function for the task of pausing the song, but still not getting the desired result.
var playButton = document.querySelector('#play-button');
var songArtist = document.querySelector('.song-artist');
var songTitle = document.querySelector('.song-name');
var stateIcon = document.querySelector('#stateicon');
var trackList = [ {
'Songartist': 'Artist1',
'Songtitle': 'Dance',
'songfile': 'Dance.mp3'
},
{
'Songartist': 'Artist2',
'Songtitle': 'Fight',
'songfile': 'Battle.mp3'
}
];
var currentSong = 0;
var song = new Audio();
function playSong() {
song.src = trackList[currentSong].songfile;
songArtist.innerText = trackList[currentSong].Songartist;
songTitle.innerText = trackList[currentSong].Songtitle;
if (song.paused) {
stateIcon.className = 'fas fa-pause';
song.play();
} else {
stateIcon.className = 'fas fa-play';
song.pause();
}
}
<body>
<div class="screen">
<div class="song-info-text">
<p class="song-artist">Some text</p>
<p class="song-name">Some more text</p>
</div>
</div>
<div class="mp3-buttons">
<button class="button" type="button" name="button"><i class="fas fa-step-backward"></i></button>
<button id="play-button" onclick="playSong()"><i id="stateicon" class="fas fa-play"></i></button>
<button onclick="nextSong()" class="button" type="button" name="button"><i class="fas fa-step-forward"></i></button>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
The snipped provided is incomplete (no element has the class "song-artist", for one). I'd suggest looking at your javascript dev console for any errors, first. Otherwise, it could be that setting the src of your audio element is resetting your audio's play state. You could try only setting the src if it's different from that of the current track.

Why aren't my HTML5 video control buttons working with Javascript?

I am working on a project using <video>, trying to make external HTML buttons play/pause, rewind slow, rewind fast, and fast forward control a video using JavaScript. I have the buttons appearing where I want them, but when I try to use them in the browser, they don't do anything to control the video, and the play button doesn't switch to pause and vice versa. I've tried for hours, looking all over the Web to find anything that I can use to help. Most solutions I find are using jQuery which I understand is easier, but it's not what I need. I just want to do it using pure JavaScript so I can better understand it. Included is my existing code. Any help on how I can get them to work would be appreciated!
HTML:
<script src="sample.js"></script>
<div class="jumbotron">
<div class="container">
<video id="video" poster="images/art/preview.png" width="100%" controls>
<source src="images/art/sample.mp4" type="video/mp4; codecs="avc1.42E01E, mp4a.40.2"">
<source src="images/art/sample.webm" type="video/webm; codecs="vp8, vorbis"">
<source src="images/art/sample.ogv" type="video/ogg; codecs="theora, vorbis"">
Your browser does not support HTML5 video
</video>
<div id="buttonbar">
<button type="button" id="fastBck">
<span class="glyphicon glyphicon-fast-backward"></span>
</button>
<button type="button" id="rew">
<span class="glyphicon glyphicon-backward"></span>
</button>
<button type="button" id="play-pause">
<span class="glyphicon glyphicon-play"></span>
</button>
<button type="button" id="fastFwd">
<span class="glyphicon glyphicon-fast-forward"></span>
</button>
</div>
</div>
</div>
JavaScript:
window.onload = function() {
var video = document.getElementById("video");
var playButton = document.getElementById("play-pause");
var rewButton = document.getElementById("rew");
var fastBckButton = document.getElementById("fastBck");
var fastFwdButton = document.getElementById("fastFwd");
}
playButton.addEventListener("click", function(){
if (video.paused==true) {
video.play();
playButton.className="glyphicon glyphicon-pause";
} else{
video.pause();
playButton.className="glyphicon glyphicon-play";
}
})
rewButton.addEventListener("click", function(){
//not sure exactly how to use currentTime to rewind, or fast forward
})
let the browser pick the right codecs for your video
you defined your variables out of scope (you've encapsulated them inside the onload function)
window.onload = function() {
var video = document.getElementById("video");
var playButton = document.getElementById("play-pause");
var rewButton = document.getElementById("rew");
var fastBckButton = document.getElementById("fastBck");
var fastFwdButton = document.getElementById("fastFwd");
playButton.addEventListener("click", function(){
if (video.paused===true) {
video.play();
playButton.className="glyphicon glyphicon-pause";
} else{
video.pause();
playButton.className="glyphicon glyphicon-play";
}
});
rewButton.addEventListener("click", function(){
//not sure exactly how to use currentTime to rewind, or fast forward
});
};
#import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");
<div class="jumbotron">
<div class="container">
<video id="video" width="100%" controls>
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg">
Your browser does not support HTML5 video
</video>
<div id="buttonbar">
<button type="button" id="fastBck"><span class="glyphicon glyphicon-fast-backward"></span></button>
<button type="button" id="rew"><span class="glyphicon glyphicon-backward"></span></button>
<button type="button" id="play-pause"><span class="glyphicon glyphicon-play"></span></button>
<button type="button" id="fastFwd"><span class="glyphicon glyphicon-fast-forward"></span></button>
</div>
</div>
</div>
Good luck with the fast forward and your other methods
window.onload = function() {
var video = document.getElementById("video");
var playButton = document.getElementById("play-pause");
var rewButton = document.getElementById("rew");
var fastBckButton = document.getElementById("fastBck");
var fastFwdButton = document.getElementById("fastFwd");
playButton.addEventListener("click", function(){
if (video.paused==true) {
video.play();
playButton.className="glyphicon glyphicon-pause";
} else{
video.pause();
playButton.className="glyphicon glyphicon-play";
}
})
rewButton.addEventListener("click", function(){
//not sure exactly how to use
currentTime to rewind, or fast forward
})
}
Move listeners inside onload function. Listeners won't be attached until the page is loaded. Respect for wanting to use vanilla JS, however unnecessary.

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 play sound on click, second button click stop first sound

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

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