1

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

DallasOiro
  • 13
  • 5
  • Try to combine the 2 conditions with a logical OR instead of AND. – IVO GELOV Apr 20 '21 at 07:27
  • I already tried it ( || ), it doesn't work either. I appreciate your try. – DallasOiro Apr 20 '21 at 07:30
  • You are creating new audio and the browser begins downloading the file `asynchronously`. It will not start playing automatically - so your checks for `played` and/or `paused` are meaningless. You should wait until enough data has been downloaded before attempting to start playing - see the documentation https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement/Audio#determining_when_playback_can_begin – IVO GELOV Apr 20 '21 at 07:43

1 Answers1

2

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

  1. you have 3 .mp3 files in the same folder as your html/js file, called: 1.mp3, 2.mp3, 3.mp3.

  2. if you place your javascript bellow HTML, BEFORE closing 'body' tag.

sinisake
  • 11,240
  • 2
  • 19
  • 27
  • 1
    Thank you for an especially a good words not even to mention a valuable help. I am trying to learn a new profession due to corona lockdowns but it goes slow. I seriously spend maybe 10-20 hours on it, but learning on the way so I don't feel the time is lost. I just want to see it working. It is still doesn't work in my case, the code seems pure I see these audio, no errors are in a log. However, I can hear only static quiet noise. I will try to understand it step by step and also this youtube video maybe has an answer "https://www.youtube.com/watch?v=E-v4SSCG6i4&list=LL&index=1". – DallasOiro Apr 20 '21 at 09:37
  • 1
    In the orignal file I was cutting a name out of an id, so guita2x becomes 2.mp3. I have it in listed in an array as '1', '2' and so on. So maybe there is a lack of connection bwtween "this.id" and fired audio from an array? – DallasOiro Apr 20 '21 at 09:40
  • Works for me, locally, tested with my .mp3's...If you don't find solution, i will make online demo, when i get back from regular work! Keep coding! :) Yes, i guess it is related to your names cutting... console.log() every var you creating, and you will get some valuable info... – sinisake Apr 20 '21 at 09:41
  • p.s. i will make demo with your slicing names... I have simplified code for the sake of clarity – sinisake Apr 20 '21 at 09:43
  • Thank you. In my case it plays all the time "else", I added a console.log. I can't help you with javascript but if you would ever have a problem with macros in excel or with inkscape, let me know. You saved me at least 10 hours of work so I want to return a favour. – DallasOiro Apr 20 '21 at 10:16
  • Np, i have changed some things, hope you will have better luck with this. – sinisake Apr 20 '21 at 15:48
  • This is how page should look now (javascript bellow)> https://pastebin.com/vRhEJiZ2 – sinisake Apr 20 '21 at 15:49
  • Unbelievable, it finally works thank to you. Now I will analyze how it works and how it differs with my code. Thank you once again. I wasn't make jokes with trying for a few days. Like I said if I ever can help you with excel building macros in excel, let me know. – DallasOiro Apr 20 '21 at 16:20