Loading and playing audio using audioContext in HTML5

Advertisemen

In this tutorial, I am just going to show you how to add, load and play audio so it is going to be very basic tutorial on AudioContext.

Step 1 :
Just drag and drop audio file into your server folder. In my case, I have ToolCool.mp3 file in the same folder of script.

<script>
function init()
{
var context = new webkitAudioContext();
BufferLoader(context, 'TooCool.mp3');
}
function finishedLoading(buff, context)
{
var source1 = context.createBufferSource();
source1.buffer = buff;
source1.connect(context.destination);
source1.start(0);
}
function BufferLoader(context, url, callback)
{
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function()
{
context.decodeAudioData(request.response,
function(buffer)
{
finishedLoading(buffer, context);
},
function(error)
{
alert('decodeAudioData error '+error);
}
);
}
request.send();
}
</script>
<div>
<button onclick="init()">Play</button>
</div>



Step 2 :
Create button and call init function which initializes AudioContext and calls BufferLoader function which has parameters - context and mp3 file we dragged into server. BufferLoader makes ajax call to the server to get that mp3 file and decodes and calls finishedLoading function to start music.

It might take a while to load and play file ...
Try here 


Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Tutorial Unity 3D