fetchAudio function takes a word and sends a post request with that data.

static async fetchAudio(word) {

const requestOptions = {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify({ "word": word })

}; let url = '/speech/';

// fetch() returns a promise that

// resolves once headers have been received

return fetch(url, requestOptions)

.then(res => {

if (!res.ok)

throw new Error(`${res.status} = ${res.statusText}`); // response.body is a readable stream.

// Calling getReader() gives us exclusive access to

// the stream's content var reader = res.body.getReader();

// read() returns a promise that resolves

// when a value has been received return reader

.read()

.then((result) => {

return result;

});

})

}

This is how we can play audio in web page.

1. Get Uint8Array response

2. Create blob url (mdn: https://developer.mozilla.org/en-US/docs/Web/API/Blob)

3. Set audio url to Audio object

4. Play audio

fetchAudio(word)

.then((response) => {

// response.value for fetch streams is a Uint8Array

var blob = new Blob([response.value], { type: 'audio/mp3' });

var url = window.URL.createObjectURL(blob)

window.audio = new Audio();

window.audio.src = url;

window.audio.play();

})

.catch((error) => {

this.setState({

error: error.message

});

});

This is the nice read on web streams.

https://jakearchibald.com/2016/streams-ftw/