How do I stop all currently playing MediaElement players? - javascript

I'm wondering how to stop all the MediaElement players currently in the DOM. I've tried this:
$('video,audio').each(function() {
$(this)[0].player.pause();
});
Let me know if that works.
A quick and dirty one, but neither work.
$(".mejs-play").live('click',function(){
$(".mejs-pause").trigger('click');
});
Tried to do my homework on this one but can't seem to find a response anymore.

Try this...
$('video, audio').each(function() {
$(this)[0].pause();
});

Here's a simple way to do a "stop all".
When first creating your MediaElement players, create them each explicity (as opposed to using $('video,audio').mediaelementplayer()):
var mediaElementPlayers = [];
$('video,audio').each(function(){
mediaElementPlayers.push(new MediaElementPlayer(this));
});
And then, when you want to stop them:
for (var i=0; i<mediaElementPlayers.length; i++){
mediaElementPlayers[i].pause(); // pause
if (mediaElementPlayers[i].getCurrentTime()){
mediaElementPlayers[i].setCurrentTime(0); // rewind
}
}

Very nice #Bart
And here is an addition to Barts function to stop audio in a certain context (within a certain element). Useful to stop media playing in a popup when it is closed for example:
function stopAudio(context) {
for (var i=0; i<mediaElementPlayers.length; i++){
if($(mediaElementPlayers[i].container).parents().find(context).length === 0) {
mediaElementPlayers[i].pause(); // pause
if (mediaElementPlayers[i].getCurrentTime()){
mediaElementPlayers[i].setCurrentTime(0); // rewind
}
}
}
}

Trigger the click event of pause button will work....check it here
$('.mejs-pause button').trigger("click");

Related

I can't make a new Audio(url).play() to stop by new Audio(url).pause()

What I want to achieve: To stop a previously started sound when a new is started. What I have now: The sounds plays simultanously, none of them is stopping. The probably reason: Wrong logic statement in a line if (audio.played && audio.paused){. Before you judge me for not trying hard enough - I am trying to solve this from 3 days, I am a beginner. It should take me a few minutes, even an hour. I tried in several combinations.At the end I listed several websites which I tried and I still haven't solved it. In all answers is something similar but still I can't made a browser to chose, always only one part is executed either audio.play() or audio.pause() in the log. It works but not as I want and these logical statements are like on other informations on the forum. At the end of the message you can see all similar topics I already tried several times. I kept just as clear code as possible and I want to do it this way, in vanilla javascript because I won't deal for now with anything more complicated. An audio url is taken from modified id on click, the audios are on my disk. It works, I made some mistake in line if (audio.played && audio.paused){ Any ideas except giving up and changing a hobby?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Timeout</title>
</head>
<script>
function playAudio3(clicked_id) {
var OriginalID = (clicked_id);
var res = OriginalID.slice(5,-1);
var audioID=res+'.mp3';
var url =audioID;
var audio = new Audio(url);
if (audio.played && audio.paused){
audio.play();
console.log('audio.play was used.');
}else {
audio.currentTime = 0
audio.pause();
console.log('audio.pause was used.');
}
}
</script>
<body>
<span id="guita2x"onclick="playAudio3(this.id);"> Guitar. </span>
<span id="piano2x" onclick="playAudio3(this.id);"> Piano. </span>
<span id="basse15x" onclick="playAudio3(this.id);"> Basse. </span>
</body>
</html>
how do i stop a sound when a key is released in JavaScript
Javascript Audio Play on click
Javascript to stop playing sound when another starts
HTML5 Audio stop function
cancel an if statement if another statement comes true
Stopping audio when another audio file is clicked using jQuery while obscuring link
https://www.w3schools.com/jsref/dom_obj_audio.asp
HTML5 Audio pause not working
Never give up, and don't change a hobby. :)
Possible solution from one hobbyist, too:
files = ['guitar', 'piano', 'bass']; // name of your files in array. You can get this array from looping through your html/spans id's too, but, this is basic logic
audios = []; //empty audios object array
for (i = 0; i < files.length; i++) {
var audioID = files[i] + '.mp3';
var url = audioID;
var audio = new Audio(url);
audios.push(audio); //place all audio objects into array
}
console.log(audios);
//now - basic logic to check which audio element to play, and to stop others
function playAudio3(clicked_id) {
for (i = 0; i < audios.length; i++) {
if (audios[i].src.includes(clicked_id)) {
audios[i].play();
} else {
audios[i].currentTime = 0
audios[i].pause();
}
}
}
So, you are creating all audio objects at the page load, and then choose which one to play. Of course, this will play all audio files from the start. If you want to keep the track of the audio progress, and play it from the last pause, you will need some additions, but, this could be the start, i hope.
OK, updated, i kept some of your code, and slightly changed some things in HTML.
Your complete code now should look like this: (HTML)
<span class='aud' id="guita1x" onclick="playAudio3(this.id);"> Guitar. </span>
<span class='aud' id="piano2x" onclick="playAudio3(this.id);"> Piano. </span>
<span class='aud' id="basse3x" onclick="playAudio3(this.id);"> Basse. </span>
Js:
spans=document.querySelectorAll('.aud');
console.log(spans);
audios = []; //empty audios object array
for (i = 0; i < spans.length; i++) {
var OriginalID = spans[i].id;
var res = OriginalID.slice(5,-1);
var audioID=res+'.mp3';
var url =audioID;
var audio = new Audio(url);
audios.push(audio); //place all audio objects into array
}
console.log(audios);
//now - basic logic to check which audio element to play, and to stop others
function playAudio3(clicked_id) {
for (i = 0; i < audios.length; i++) {
clickid=clicked_id.replace(/[A-Za-z]/g,'')+'.mp3';
if (audios[i].src.includes(clickid)) {
audios[i].play();
} else {
audios[i].currentTime = 0
audios[i].pause();
}
}
}
Now, i have just added class 'aud' to your spans, for easier targeting.
Then, i have collected id's from the spans and placed it in the audios array. (Not sure why you are slicing names/ids, you can simplify things by adding just numbers: 1, 2, 3 and so on).
NOW, this MUST work, IF
you have 3 .mp3 files in the same folder as your html/js file, called: 1.mp3, 2.mp3, 3.mp3.
if you place your javascript bellow HTML, BEFORE closing 'body' tag.

JavaScript audio object stopping in the middle of playing

In a project I'm working on, I have a JS file that should play a piece of music, and when that piece is done playing, the next one takes its place.
var soundtrack = {
0: new Audio("./music/piece1.ogg"),
2: new Audio("./music/piece2.ogg"),
1: new Audio("./music/piece3.ogg"),
3: new Audio("./music/piece4.ogg")
}
var currentTrack = 0;
function startMusic(){
soundtrack[currentTrack].play();
soundtrack[currentTrack].addEventListener("ended", function(){ nextSong()});
}
function nextSong(){
currentTrack += 1;
if(currentTrack == 4){
currentTrack = 0;
}
soundtrack[currentTrack].play();
}
$( document ).ready(function() {
setTimeout(function() { startMusic(); }, 15500);
});
My use of the object "soundtrack" may be unconventional, but there was a bug using an array so I tried this and it worked.
The first piece plays through fine, and the next one starts up fine. About maybe 10 seconds in, the playing just stops.
Any help to solve this issue would be greatly appreciated, thanks!
Note: I am aware not all pieces will play after one other, I'm waiting until this issue is fixed before continuing.

player plays two times on first click

I am having a tough time I have a code where you click on a image and if it possible to move it to next cell the it should move
function changecell(a){
var moved=false;
if(a%3 !=0) {
if(ij[a-1]==0) {
moved=true;
if(moved==true) {
no=firstmove++;
move.innerHTML = no;
playTick();
}
swap(a-1,a);
}
}
if((a+1)%3 !=0 && moved==false) {
if(ij[a+1]==0) {
moved=true;
if(moved==true) {
no=firstmove++;
move.innerHTML = no;
playTick();
}
swap(a+1,a);
}
}
}
function playTick() {
document.getElementById('tickSound').play();
}
function swap(x1,x2) {
var temp=ij[x1];
ij[x1]=ij[x2];
ij[x2]=temp;
var p = eval("document.images.i"+x1);
p.src="images1/"+ij[x1]+".png";
p = eval("document.images.i"+x2);
p.src="images1/"+ij[x2]+".png";
}
my problem is for first click the sound plays for two times and then after that it plays once as it is supposed to play.
Does anybody have any idea about this?
EDIT:
I did put an alert() in the if(moved==true) loop the alert shows only for once but sound plays twice. Suppose the if(moved==true) was getting executed again wouldn't I get another alert()?
I'm thinking that both the if conditions are being satisfied on the first run so the playTick() method is being called twice. Without knowing the value of a, i cannot be sure.

How do I stop a image gallery from running onClick?

I have a site that has an image gallery that changes images every few seconds using JavaScript; however, I want to know how to STOP the images from changing when a user clicks on one of the images.
So far, the images are rotating as planned, but I can't seem to get the "onClick" scripting to STOP the rotation when the user clicks on an image. I don't need to have an alert popup or need it to do anything, I just need it to STOP the image rotation when someone clicks on one of the pictures.
Here's the HTML code I have:
else (getValue=='STOP')
{
alert("STOPPED");
}
That won't do what you probably want it to do. It should be:
else if (getValue=='STOP')
{
alert("STOPPED");
}
First of all, you missed out on the keyword "IF" in one of the lines of your code.
However, the way to create a terminable repetitive action is to setInterval and then use clearInterval to terminate the repetition.
semaphore = setInterval(somefunction, someinterval);
clearInterval(semaphore);
Example (I wrote this off-the-cuff, so there might be some errors, but you shd get the idea):
<img src="./images/image1.jpg" id="imageGallery" name="imageGallery"
onclick="chooseImg(this)" />
<script>
var turn = setInterval(function(){imgTurn()},5000);
var images = function2CreateImgArray();
var imageN = 0;
function chooseImg(img){
clearInterval(turn);
function2DisplayImg(imageN); // or do whatever
}
function imgTurn(){
if (imageN++ >= images.length) imageN = 0;
function2DisplayImg(imageN++);
}
</script>
You could replace the setInterval with setTimeout.
var turn = setTimeout(function(){imgTurn()},5000);
But then you need to use clearTimeout to stop it:
clearTimeout(turn);
But if you use setTimeout, you would need to setTimeout for the next image display, so you would not even need to clearTimeout to stop the rotation.
<img src="./images/image1.jpg" id="imageGallery" name="imageGallery"
onclick="chooseImg(this)" />
<script>
setTimeout(function(){imgTurn()},5000);
var images = function2CreateImgArray();
var imageN = 0;
var turn = 1;
function chooseImg(img){
turn = 0;
function2DisplayImg(imageN); // or do whatever
}
function imgTurn(){
if (turn==0) return;
if (imageN++ >= images.length) imageN = 0;
function2DisplayImg(imageN++);
}
</script>

Starting and Stopping Audio in Javascript

I have a function tied to an onClick event. It's supposed to play a song. If there's a song already playing it's supposed to stop the current song and start playing the new one. The only problem is that as far as I know there is only a pause method and it means that the previous song will resume from the paused position and not the beginning. Is there any way around this (like a .stop() method)?
Here's my code:
var currSong="";
function playSong(newSong){
alert(newSong);
if (newSong != ""){
if(currSong != "" ) {
document.getElementById(currSong).pause();
}
document.getElementById(newSong).play();
currSong = newSong;
}
}
From looking at the MDC documentation for the audio element, it appears that the correct way to do this is by setting the currentTime property:
function playSong(newSong){
alert(newSong);
if (newSong != ""){
if(currSong != "" ) {
document.getElementById(currSong).pause();
}
var newSongEl = document.getElementById(newSong);
newSongEl.currentTime = 0;
newSongEl.play();
currSong = newSong;
}
}
Also, it would be better to store the relevant element in currSong, rather than its ID, unless you are using the ID for something else.

Categories