Функция fetchAudio принимает слово и отправляет почтовый запрос с этими данными.
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; }); }) }
Вот как мы можем воспроизводить аудио на веб-странице.
1. Получите ответ Uint8Array
2. Создайте URL-адрес большого двоичного объекта (mdn: https://developer.mozilla.org/en-US/docs/Web / API / Blob )
3. Установите URL-адрес аудио как объект Audio
4. Воспроизвести аудио
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 }); });
Это приятное чтение в веб-потоках.
https://jakearchibald.com/2016/streams-ftw/