Created
September 26, 2017 14:49
-
-
Save idettman/1aed3c42a836661c84752add5d7c7f86 to your computer and use it in GitHub Desktop.
WebAudio simple example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ul> | |
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-leadguitar.mp3">Lead Guitar</a></li> | |
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-drums.mp3">Drums</a></li> | |
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-bassguitar.mp3">Bass Guitar</a></li> | |
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-horns.mp3">Horns</a></li> | |
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-clav.mp3">Clavi</a></li> | |
</ul> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.AudioContext = window.AudioContext || window.webkitAudioContext; | |
var offset = 0; | |
var context = new AudioContext(); | |
function playTrack(url) { | |
var request = new XMLHttpRequest(); | |
request.open('GET', url, true); | |
request.responseType = 'arraybuffer'; | |
var audiobuffer; | |
// Decode asynchronously | |
request.onload = function() { | |
if (request.status == 200) { | |
context.decodeAudioData(request.response, function(buffer) { | |
var source = context.createBufferSource(); | |
source.buffer = buffer; | |
source.connect(context.destination); | |
console.log('context.currentTime '+context.currentTime); | |
if (offset == 0) { | |
source.start(); | |
offset = context.currentTime; | |
} else { | |
source.start(0,context.currentTime - offset); | |
} | |
}, function(e) { | |
console.log('Error decoding audio data:' + e); | |
}); | |
} else { | |
console.log('Audio didn\'t load successfully; error code:' + request.statusText); | |
} | |
} | |
request.send(); | |
} | |
var tracks = document.getElementsByClassName('track'); | |
for (var i = 0, len = tracks.length; i < len; i++) { | |
tracks[i].addEventListener('click', function(e){ | |
console.log(this.href); | |
playTrack(this.href); | |
e.preventDefault(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment