SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot moretea's Avatar
    Join Date
    Jun 2004
    Location
    Texas, USA
    Posts
    118
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    How to pause or remove a dynamically created HTMLAudioElement?

    I'm trying to create an audio playlist from a <select> element. There is one critical piece to the puzzle that I'm missing; if a selection is playing, how can I stop it and replace the .src attribute with a new .src?

    The problem seems to be rooted in the way I create the audio element...
    Code:
    if (window.Audio) { 
                    auPlayer = new Audio; 
                    } else {                 
        auPlayer = new HTMLAudioElement;             
        }
    The first thing I should do in the script is check for the existence of one of these audio elements and stop/pause it. I've looked for a way to search the DOM for these elements, but with no luck. The complete source is below; can anyone help me out of the mess I've created? Thanks in advance!

    Code:
    <!-- HTML -->
                <div class="well well-sm" id="au">
        <form id="frm_au" name="frm_au">
            <select id="sel_au" name="sel_au" size="3">
                <option data-mp3src="_bin/unforgettable.mpg" data-oggsrc="_bin/unforgettable.ogg" value="Unforgettable">Unforgettable</option>
                <option data-mp3src="_bin/at_last.mp3" data-oggsrc="_bin/at_last.ogg" value="At Last">At Last</option>
                <option data-mp3src="_bin/sunshineofmylife.mp3" data-oggsrc="_bin/sunshineofmylife.ogg" value="You Are The Sunshine Of My Life">You Are The Sunshine Of My Life</option>
                <option data-mp3src="_bin/astimegoesby.mp3" data-oggsrc="_bin/astimegoesby.ogg" value="As Time Goes By">As Time Goes By</option>
                <option data-mp3src="_bin/cantaloupeisland.mp3" data-oggsrc="_bin/cantaloupeisland.ogg" value="Cantaloupe Island">Cantaloupe Island</option>
                <option data-mp3src="_bin/Bethlehem.mp3" data-oggsrc="_bin/Bethlehem.ogg" value="O Little Town Of Bethlehem">O Little Town Of Bethlehem</option>
                <option data-mp3src="_bin/silentnite.mp3" data-oggsrc="_bin/silentnite.ogg" value="Silent Night">Silent Night</option>
                <option data-mp3src="_bin/letitsnow.mp3" data-oggsrc="_bin/letitsnow.ogg" value="Let It Snow!">Let It Snow!</option>                  
            </select>
        </form>
        <div id="myAudioContainer"></div>
      </div>
    
    <!-- JavaScript -->
    <script src="../js/modernizr.custom.js"></script> <!-- yes, this is in the <head> of the page -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script><script>
    function playAudio() {
        $('audio').remove(); // This is not working!
        var oggsrc = $('option:selected', this).data('oggsrc');
        var mp3src = $('option:selected', this).data('mp3src');
        console.log(oggsrc + ', ' + mp3src);
        var title = $(this).val();
        // Can play HTML5 audio?
        if (!Modernizr.audio) {
            fallbackHtml = "Your browser cannot natively play audio. <a href='" + mp3src + "'>Download " + title + " here</a>.";
            $('#myAudioContainer').html(fallbackHTML);
        } else {
            if (Modernizr.audio.mp3) {
                audioSrc = mp3src;
            } else {
                if (Modernizr.audio.ogg) {
                    audioSrc = oggsrc;
                } else {
                    fallbackHtml = "We cannot determine what audio format is supported by your browser. <a href='" + mp3src + "'>Download " + title + " here</a>.";
                    $('#myAudioContainer').html(fallbackHTML);
                }            
            };
        };
    
        var auPlayer;
        if (window.Audio) {
        auPlayer = new Audio;
        } else {
            auPlayer = new HTMLAudioElement;
        }
        auPlayer.src = audioSrc;
        auPlayer.autoplay = true;
        auPlayer.load();
        auPlayer.play();
        btnPause = document.createElement('button');
        $(btnPause).addClass('btn-warning').text('Pause ' + title);
        $(btnPause).appendTo($('#myAudioContainer'));
        $(btnPause).on('click',function() {
            auPlayer.pause();
            $('#myAudioContainer').empty('button');
        })
    }
    $(document).ready(function() {
        $('#sel_au').click(playAudio);
    });
    </script>

  2. #2
    SitePoint Zealot moretea's Avatar
    Join Date
    Jun 2004
    Location
    Texas, USA
    Posts
    118
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Well, I never did find an answer on how to pause and/or remove a dynamically created HTMLAudioElement. I finally conceded that I was going to have to create the <audio> element in HTML. Here's my solution:

    HTML:
    Code:
    <select id="sel_au" name="sel_au" size="3">           			
        <option data-mp3src="_bin/unforgettable.mp3" data-oggsrc="_bin/unforgettable.ogg" value="Unforgettable">Unforgettable</option>           			
        <option data-mp3src="_bin/at_last.mp3" data-oggsrc="_bin/at_last.ogg" value="At Last">At Last</option> 
        <!-- et cetera... -->
    JavaScript:
    Code:
    <script>
    
    	function selSrc(ele) {
    		if (Modernizr.audio) {
    			var mySrc, mp3src, oggsrc;
    			mp3src = $(ele).children("option").filter(":selected").data('mp3src');
    			oggsrc = $(ele).children("option").filter(":selected").data('oggsrc');
    			mySrc = Modernizr.audio.ogg ? oggsrc : mp3src;
    			return mySrc;
    		} else {
    			$('#myPlayr').html('<strong>SO SORRY!</strong> Your browser is not up to date and does not natively support audio. Try installing <a href="http://www.firefox.com">Firefox</a> or <a href="http://chrome.google.com">Chrome</a>. In the meantime, you may download your selection below.');
    			strFallback = '<ul>';
    			for (i = 0; i < $(ele).options.length; i++) {
    				strFallback += '<li><a href="' + $(ele).options[i].data('mp3src') + '">' + $(ele).options[i].val() + '</a></li>';
    			}
    			strFallback += '</ul>';
    			$('#fallback').html(strFallback);
    			return false;
    		}
    	}
    	function playSel(mySel) {
    		myPlayr = document.getElementsByTagName('audio')[0];
    		if (myPlayr.src != undefined) {
    			myPlayr.pause();
    			myPlayr.src = mySel;
    		} else {
    			myPlayr.src = mySel;
    		}
    		myPlayr.load();
    		myPlayr.play();
    	}
    	
    	$(document).ready(function() {
    		$('#sel_au').on('click', function() {
    			playSel(selSrc($(this)));
    		});
    	});
    	</script>
    I welcome any suggestions for improvements!


Bookmarks

Posting Permissions

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