Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play a binary string with the HTML audio tag

I have a server that serves ogg encoded audio to a client that requests it with a http GET. If I inject the GET route into the HTML audio src it receives the audio and plays it:

function working(text) {
    var downloadURL = 'http://localhost:8080/nlc/synthesize' +
        '?text=' + encodeURIComponent(text);

    audio.pause();
    audio.src = downloadURL;
    audio.play();

};

If I use a http GET call (in AngularJS) and try to inject the response into the HTML audio src it won't play it:

function not_working(text) {
  $http.get('http://localhost:8080/nlc/synthesize' + '?text=' + encodeURIComponent(text)).then(function(response) {
      console.log(response);
      audio.pause();
      audio.src = encodeURIComponent(response);
      audio.play();

};

The log of the response shows a JSON with a binary string at the 'data' key:

Object {data: "OggS�1�/ڂ OpusHead��]OggS…�xs���������������������������������", status: 200, config: Object, statusText: "OK"}

Is there a way to decode the http GET response into something I can inject into the audio src?

like image 848
trahloff Avatar asked Apr 20 '16 08:04

trahloff


People also ask

How do I play audio in HTML?

The HTML <audio> element is used to play an audio file on a web page.

Can we play audio in HTML?

The below Examples explain the audio Tag: Example 1 (Adding audio to Webpage): The controls attribute is used to add audio controls such as play, pause, and volume. The “source” element is used to specify the audio files which the browser may use. The first recognized format is used by the browser.

What is the HTML tag for audio files?

The <audio> tag is used to embed sound content in a document, such as music or other audio streams.

What is .OGG in HTML?

Ogg is a free, open container format maintained by the Xiph.Org Foundation. The authors of the Ogg format state that it is unrestricted by software patents and is designed to provide for efficient streaming and manipulation of high-quality digital multimedia.


1 Answers

I finally managed to do it with this code:

function working(text) {
    var url = 'http://localhost:8080/nlc/synthesize';
    var req = {
        method: 'POST',
        url: url,
        responseType: 'blob',
        data: {
            "text": text
        },
        headers: {
            'Content-Type': 'application/json',
        }
    }

    $http(req).then(function(response) {
        console.log(response);
        audio.pause();
        audio.src = URL.createObjectURL(response.data);
        audio.play();
    })
};
like image 103
trahloff Avatar answered Oct 26 '22 20:10

trahloff