How to make the melody play when you click on the button? This is an option, but when you click again, the melody is played again, not reset. How to make it?

<a href="#" onclick="new Audio('http://www.html5tutorial.info/media/vincent.mp3').play(); return false;">Play</a> 

    4 answers 4

    "Jump" javascript to the object that represents the button. You hang up on the button the function handler for the onclick event. Here is the function:

     function sound() { var audio = new Audio(); // Π‘ΠΎΠ·Π΄Π°Ρ‘ΠΌ Π½ΠΎΠ²Ρ‹ΠΉ элСмСнт Audio audio.src = '...'; // Π£ΠΊΠ°Π·Ρ‹Π²Π°Π΅ΠΌ ΠΏΡƒΡ‚ΡŒ ΠΊ Π·Π²ΡƒΠΊΡƒ "ΠΊΠ»ΠΈΠΊΠ°" audio.autoplay = true; // АвтоматичСски запускаСм } 

      Alternatively, you can use the audio tag. It already has controls in place.

       <audio src="http://www.html5tutorial.info/media/vincent.mp3" controls></audio> 

        For the button to work as Play / Pause, you need to track the current state of the player. It may be:

        1. didn't start playing
        2. plays
        3. paused
        4. the track finished the game

        Below is a clumsy example where the label on the button changes, depending on the state: Play, Playing, Paused, Done:

         var el = document.getElementById('btn-play'); var playing = false; // Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π΅ состояниС ΠΏΠ»Π΅Π΅Ρ€Π° var player = new Audio('http://www.html5tutorial.info/media/vincent.mp3'); player.preload = "auto"; player.addEventListener('ended', function(){ // ΡΠ»ΡƒΡˆΠ°Π΅ΠΌ ΠΎΠΊΠΎΠ½Ρ‡Π°Π½ΠΈΠ΅ Ρ‚Ρ€Π΅ΠΊΠ° el.innerText = "Done"; playing = false; }); el.addEventListener('click', playPause); // ΡΠ»ΡƒΡˆΠ°Π΅ΠΌ Π½Π°ΠΆΠ°Ρ‚ΠΈΠ΅ Π½Π° ΠΊΠ½ΠΎΠΏΠΊΡƒ function playPause() { if( playing) { player.pause(); el.innerText = "Paused"; } else { player.play(); el.innerText = "Playing.."; } playing = !playing; } 
         <link href="https://yastatic.net/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <button id="btn-play" class="btn btn-success">Play</button> 

          You simply create several objects and launch them. It is necessary somewhere to store the object of the current playback and overwrite it.

          Example:

           var audio = {}; function startAudio(url) { if("pause" in audio) audio.pause(); audio = new Audio(url); audio.play(); } 
           <a href="#" onclick="startAudio('http://goo.gl/UWLwi1'); return false;">Play</a> 

          • FireFox 48.0 / OS X: repeated presses lead to parallel launch of copies of the sound. "This will be the progress of the audio recording." - Sergiks
          • It meant audio = audio || new Audio(url); audio = audio || new Audio(url); ? - Qwertiy ♦
          • @ Mihanik71 And how are you going to stop, it seems to me that after that the user will not return to the site) - user192664
          • Corrected the answer. - Mihanik71
          • @NikitaSmith and if a person just needs to play a sound such as a sent image. Answered as understood the question - Mihanik71