Search code examples
javascriptphpjqueryweb-audio-api

Web Audio API Delayed Buffer Playback


this is my first interaction in this portal. I have learnt that this portal is made by developers and for developers.

I have a very peculiar problem which I was trying to solve since last 1 month. But unfortunately, I couldn't find the exact solution. The problem is, I have a music streaming website from which users will listen songs online. I don't have a web music player for my website yet, so was developing one.

Recently I implemented Web Audio API into my website for streaming. Which works very well but it does not start playing the stream buffer immediately when it receives from server.

I am handling the requests dynamically at server which does not provide the direct link to the resource, whereas I am reading the file in php and streaming for example readfile() or fopen() and fread() etc.

I am receiving the content very well but problem is the api does not start playing the buffer immediately but it plays the stream when the whole content is received.

If the song is 5mb, audio api buffers all 5mb and later on starts to play. I want it to play immediately after some stream received.

My javascript is as below

if(a.status==true&&b=='success'){
                (processView.audioCtx)?processView.audioCtx.close():'';
                processView.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                processView.songSrc = processView.audioCtx.createBufferSource();
                var request = new XMLHttpRequest();
                request.open('GET', processView.playSong.mp3, true);
                request.responseType = 'arraybuffer';
                request.onload = function(a) {
                    var audioData = request.response;
                    processView.audioCtx.decodeAudioData(audioData, function(buffer) {
                        processView.songSrc.buffer = buffer;
                        //processView.songbuffer = processView.songSrc.buffer;
                        processView.songSrc.connect(processView.audioCtx.destination);
                        processView.songSrc.loop = true;
                        processView.songSrc.start(0);
                        $('#togglePlayerBtn').attr('state','playing').html('<span class="fa fa-pause"></span>').css('background','transparent');
                        //processView.audioCtx.onstatechange = processView.handlePlayer();
                    },
                    function(e){ console.log("Error with decoding audio data" + e.err); });
                }
                request.send();

My php file at server side is as below

$mime_type = "audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3";
        if(file_exists($path)){
            header('Content-type: {$mime_type}');
            header('Content-length: ' . filesize($path));
            header('Content-Disposition: filename="' . $fileName);
            header('X-Pad: avoid browser bug');
            header('Cache-Control: no-cache');
            readfile($path);
            exit;
        }
        else
        {
            header('Error: Unknown Source',true,401);
            echo 'File not found !';
        }

I am really thankful to this portal where I could get the solutions to my problems.

Thank You, -- HKSM


Solution

  • The solution was simple, I split the mp3 file at server level and send one by one to the browser requesting...

    I amended javascript as below ..

    updateSongBuffer    : function(){
        if(processView.songSrc.length < 1)processView.songSrc = new Array();
        var request = new XMLHttpRequest();
        processView.songLength++;
    // here i am requesting file parts one by one...
        request.open('GET', processView.playSong.mp3+'/'+processView.songLength, true);
        request.responseType = 'arraybuffer';
        request.onprogress = function(){
            $('#togglePlayerBtn').css('background','url(/images/mloading.gif) no-repeat center center').css('background-size','cover');
        },
        request.onload = function(a) {
            $('#togglePlayerBtn').css('background','transparent');
            var audioData = request.response;
            processView.songSrc[processView.songLength] = processView.audioCtx.createBufferSource();
    
                processView.audioCtx.decodeAudioData(audioData).then(function(buffer) {
                //processView.audioCtx.decodeAudioData(audioData, function(buffer) {
    
                processView.songSrc[processView.songLength].buffer = buffer;
    
                processView.songSrc[processView.songLength].connect(processView.audioCtx.destination);
    
                if(processView.songSrc[processView.songLength-1]){
                    processView.totalDuration += processView.songSrc[processView.songLength-1].buffer.duration;
                }
                else
                {
                    processView.totalDuration += processView.audioCtx.currentTime;
                }
    
                processView.songSrc[processView.songLength].start(processView.totalDuration);
    // here i am calling the same function if audio data decoded and buffer is set successfully . . . By doing this, everything is working fine now.
                processView.timeoutFunc = setTimeout('processView.updateSongBuffer()',10000);       
            },
            function(e){ console.log("Error with decoding audio data ...");console.log(e);});
         }
         request.send();
    },
    

    Anyways, thank you very much to all.