Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Web Audio API not playing a mp3 file?

I'm trying to follow a tutorial online by piecing together the examples. I feel like this should be playing the mp3 file. I'm using the Chrome browser and it's up to date. I don't get any errors on the console. I'm not sure what I need to change or add to make this work.

<script type="text/javascript">

//creating an audio context

window.addEventListener('load',init);

function init()
{

    try
    {
        window.AudioContext = window.AudioContext || window.webkitAudioContext;
        var context=new AudioContext();

    }
    catch(e)
    {
        alert("Your browser doesn't support Web Audio API");
    }

    loadSound();
    playSound();
}

//loading sound into the created audio context

function loadSound()
{
    //set the audio file's URL
    var audioURL='audio files/song.mp3';

    //creating a new request
    var request = new XMLhttpRequest();
    request.open("GET",audioURL,true);
    request.responseType= 'arraybuffer';
    request.onLoad funtion(){

        //take the audio from http request and decode it in an audio buffer

        var audioBuffer = null;

        context.decodeAudioData(request.response, function(buffer){ audioBuffer= buffer;});

    }

    request.send();

}, onError);

//playing the audio file
function playSound(buffer) {
  //creating source node
  var source = audioContext.createBufferSource();
  //passing in file
  source.buffer = audioBuffer;

  //start playing
  source.start(0);
}

</script>

</head>


</html>
like image 517
Juhi Davda Avatar asked Dec 21 '14 12:12

Juhi Davda


People also ask

How to load audio files in JavaScript?

You may also load a sound file with JavaScript, with new Audio() . const audio = new Audio("freejazz. wav");


2 Answers

You are using async XMLHttpRequest (note that it should be spelled by capital "H"), so most probably playSound function is called before request.onLoad (note: missing =) completes.

Try to trace execution of your script using console.log or similar to find bugs like this and use JavaScript Console to catch syntax errors.

like image 155
el.pescado - нет войне Avatar answered Sep 29 '22 14:09

el.pescado - нет войне


i got this thing fixed :) i made use of audio tag along with web audio API. here's the code :

var audio = new Audio();
audio.src = 'audio files/song.mp3';
audio.controls = true;
audio.autoplay = true;
document.body.appendChild(audio);

var context = new webkitAudioContext();
var analyser = context.createAnalyser();


window.addEventListener('load', function(e) {
  // Our <audio> element will be the audio source.
  var source = context.createMediaElementSource(audio);
  source.connect(analyser);
  analyser.connect(context.destination);


}, false);

thnks for trying to help :))

like image 21
Juhi Davda Avatar answered Sep 29 '22 14:09

Juhi Davda