JavaScript - HTML5 Audio

Aus Wikizone
Wechseln zu: Navigation, Suche

Quelle: http://9elements.com/html5demos/audio/ (2013-2)

HTML Audio Player

<audio controls autobuffer>
  <source src="thankyou.ogg" />
  <source src="thankyou.mp3" />
  <!-- oder doch Flash?! -->
</audio>

Steuerung eines Audio Elements mit JavaScript

// wir definieren eine Variable welche in allen Closures gilt			
var audioElement;

// start the audio element
$('#start-audio-button').click(function() {
	// Audioelement erstellen
	audioElement = new Audio("");
	
	// im DOM einfügen, sonst wird es nicht abgespielt
	document.body.appendChild(audioElement);
	
	// herausfinden welcher Medientyp abgespielt werden kann
	var canPlayType = audioElement.canPlayType("audio/ogg");
	if(canPlayType.match(/maybe|probably/i)) {
		audioElement.src = 'thankyou.ogg';
	} else {
		audioElement.src = 'thankyou.mp3';
	}
	
	// erst abspielen wenn genug vom mp3 geladen wurde
	audioElement.addEventListener('canplay', function() {
		audioElement.play();
	}, false);

	// Funktionen erst einblenden
	$('#realtime-functions').animate({ opacity : '1.0'}, 400);

	// jetzt die anderen Events binden
	// pause
	$('#pause-button').click(function() {		
		audioElement.pause();
		return false;
	});

	// play
	$('#play-button').click(function() {		
		audioElement.play();
		return false;
	});

	// zufällige Lautstärke
	$('#change-volume-button').click(function() {	
		var volume = Math.random(); // Wert zwischen 0..1
		audioElement.volume = volume;
		$('#volume').text(Math.floor(volume*100));
		return false;
	});

	return false;
});

Abfrage der Fähigkeiten des Userbrowsers


try {
    myAudioObj = new Audio(""); 

    audioObjSupport = !!(myAudioObj.canPlayType);
    basicAudioSupport = !!(!audioObjSupport ? myAudioObj.play : false);

	if (myAudio.canPlayType) {
	   // Currently canPlayType(type) returns: "no", "maybe" or "probably"
	    canPlayOgg = ("no" != myAudio.canPlayType("audio/ogg")) && ("" != myAudio.canPlayType("audio/ogg"));
	    canPlayMp3 = ("no" != myAudio.canPlayType("audio/mpeg")) && ("" != myAudio.canPlayType("audio/mpeg"));
	}
} catch (e) {
    audioObjSupport = false;
    basicAudioSupport = false;
}


Links

http://blogs.msdn.com/b/ie/archive/2011/05/13/unlocking-the-power-of-html5-lt-audio-gt.aspx

Synchronisation, Preloading, Multiple Files