Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting html5 media source using ajax

I needed to aid authentication headers for my audio files i was grabbing from a external server. So now im trying to use ajax, i can grab the files fine, but i cant set them as the media source for my player. How do you approach setting a ajax loaded file as a audio source?

EDIT

Ended up fixing it in case someone comes back this way.

if (this.mAudioPlayer.canPlayType("audio/mpeg")) {
    this.mExtension = '.mp3';
}else if (this.mAudioPlayer.canPlayType("audio/ogg")) {
    this.mExtension = '.ogg';
} else if (this.mAudioPlayer.canPlayType("audio/mp4")) {
    this.mExtension = '.m4a'; 
}

this.CreateAudioData = function() {

    //downloading audio for use in data:uri
    $.ajax({
        url: aAudioSource + this.mExtension + '.txt',
        type: 'GET',
        context: this,
        async: false,
        beforeSend: function(xhr) {xhr.setRequestHeader('Authorization', window.userId);},
        success: this.EncodeAudioData,
        error: function(xhr, aStatus, aError) { HandleError('Audio Error: ' + aStatus); }
    });
};

this.EncodeAudioData = function(aData) {
    //this.mAudioData = base64_encode(aData);
    this.mAudioData = aData;

    if (this.mExtension == '.m4a') {
        Debug("playing m4a");
        this.mAudioSrc = "data:audio/mp4;base64," + this.mAudioData;
    } else if (this.mExtension == '.ogg') {
        Debug("playing ogg");
        this.mAudioSrc = "data:audio/ogg;base64," + this.mAudioData;
    } else if (this.mExtension == '.mp3') {
        Debug("playing mp3");
        this.mAudioSrc = "data:audio/mp3;base64," + this.mAudioData;
    }

};

this.play = function() {

    if (this.mAudioPlayer.src != this.mAudioSrc) {
        this.mAudioPlayer.src = this.mAudioSrc;
    }
    this.mAudioPlayer.load();
    this.mAudioPlayer.play();
};

Had to do asynch:false, otherwise i would get a small chunk of the audio instead of all of it. Though removing the asynch made debugging easier in the end.

like image 952
Neablis Avatar asked Sep 17 '12 22:09

Neablis


1 Answers

Are you actually downloading the file, or returning it in base64 encoded format (i.e. as a Data URI)?

Changing the source of an audio element via JavaScript is quite straightforward.

<audio id="myAudio" controls />

And then once you have the source,:

var audio = document.getElementById("myAudio");
audio.src = myAudioFile;
audio.type = "type/ogg"; // ony showing an OGG example here
like image 56
Ian Devlin Avatar answered Oct 26 '22 14:10

Ian Devlin