Daniel Santos
Daniel Santos

Reputation: 15968

How to set loaded audio to a HTML Audio tag controller?

I am using a Azure speech services to load a TTS from an ajax post.

function tts(data){

    var url = "https://speech.platform.bing.com/synthesize"
    var headers = {
            "X-Microsoft-OutputFormat":"audio-16khz-64kbitrate-mono-mp3",
            "Content-Type":"application/x-www-form-urlencoded",
            "Authorization":"Bearer " + JWT // My Jason Token
        }

        $.ajax({
            url: url,
            type: 'post',
            data: data, // The text for speech
            headers: headers,
            success: function (data) {
                audiodata = data;
            }
        });
}

The audiodata contains the loaded mpeg audio data. How can I put this data into a <audio> HTML tag?

Upvotes: 0

Views: 316

Answers (1)

Aaron Chen
Aaron Chen

Reputation: 9950

You can use the following Javascript code sample to do that:

function tts(data) {

    var url = "https://speech.platform.bing.com/synthesize"

    var oReq = new XMLHttpRequest();
    oReq.open("POST", url, true);
    oReq.responseType = "blob";

    oReq.setRequestHeader("X-Microsoft-OutputFormat", "audio-16khz-64kbitrate-mono-mp3");
    oReq.setRequestHeader("Content-Type", "application/ssml+xml");
    oReq.setRequestHeader("Authorization", "Bearer " + JWT)

    oReq.onload = function (oEvent) {
        var blob = oReq.response; // Note: not oReq.responseText
        if (blob) {
            var audioObj = document.getElementById('audiotag');
            audioObj.src = window.URL.createObjectURL(blob);
            audioObj.play();
        }

    };

    oReq.send(data);    
}

And the HTML page should include the content below:

<audio id="audiotag"></audio>

Upvotes: 1

Related Questions