www.webdeveloper.com
Results 1 to 2 of 2

Thread: <audio> stop() playing all other instances.

Hybrid View

  1. #1
    Join Date
    Mar 2010
    Location
    Finland
    Posts
    88

    <audio> stop() playing all other instances.

    Hi, I was wondering if someone could show me a way to stop an existing instance of a sound file when another is called -- ie. only one sound file playing at a time.

    Here some code I played with to call multiple sound files on a page...

    HTML Code:
    <!DOCTYPE html>
    <html>
    <body>
    
    <audio id="1"> 
      <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4" type='audio/mp4'> 
      <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga" type='audio/ogg; codecs=vorbis'>
      Your user agent does not support the HTML5 Audio element.
    </audio>
    
    <audio id="2"> 
      <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4" type='audio/mp4'> 
      <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga" type='audio/ogg; codecs=vorbis'>
      Your user agent does not support the HTML5 Audio element.
    </audio>
    
    
    <button type="button" onclick="aud_play_pause('1')">Listen</button>
    <button type="button" onclick="aud_play_pause('2')">Listen</button>
    
    <script>
    
    function aud_play_pause(idNumber) {
      var idNumber = document.getElementById(idNumber);
      if (idNumber.paused) {
        idNumber.play();
      } else {
        idNumber.pause();
      }
    }
    
    </script>
    
    
    </body>
    </html>
    I guess I could put my ids in a array and then iterate through them calling stop() on each one (before playing the selected audio file), but perhaps there is an easier way?

    Thanks.

  2. #2
    Join Date
    Mar 2010
    Location
    Finland
    Posts
    88
    Ok, much pondering was done, and I came up with...
    Code:
    ids = new Array(2); // an array with total number of ids
    
    function aud_play_pause(idNumber) {
    
      var idNumber = document.getElementById(idNumber);
    	
      for(var i=0; i<ids.length; i++){
        document.getElementById(i+1).pause(); // Pause all ids before playing next file.
        document.getElementById(i+1).currentTime = 0; // Set the time back to zero, else it will replay from the pause point.
      }
    
      idNumber.play();
    }
    Not as bad as I expected. If anyone has a more elegant way (if that's the correct term), feel free to post.

    Thanks

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles