一、接口設(shè)置
// 語(yǔ)音播放
export const getVoicePlay = (content: string) => {
return requestVoice({
url: '/tts/?text_prompt=' + content,
method: 'get',
responseType: 'blob', // 返回類型blob
});
};
二、數(shù)據(jù)處理播放
getVoicePlay(item.content).then((res: any) => {
console.log(res);
const blob = new Blob([res], { type: 'audio/wav' });
const localUrl = (window.URL || webkitURL).createObjectURL(blob);
const audio = document.createElement('audio');
audio.style.display = 'none'; // 防止影響頁(yè)面布局
audio.controls = true;
document.body.appendChild(audio);
audio.src = localUrl;
audio.playbackRate = 1.3; // 語(yǔ)速
audio.play();
// 語(yǔ)音播放完畢后,需要手動(dòng)釋放內(nèi)存
audio.onended = function () {
document.body.removeChild(audio);
URL.revokeObjectURL(localUrl);
};
});
三、本地音頻資源播放
如果我們要使用本地的音頻資源,在 vue3 中那么我們需要對(duì)資源的地址做一下處理文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-768648.html
// 動(dòng)態(tài)獲取本地的音頻資源路徑
const getWav = (index: number) => {
return new URL(`/voice/voice${index}.wav`, import.meta.url).href;
};
// 播放音頻
const playVoice = (index: number) => {
const wavFile = getWav(index);
const audio = document.createElement('audio');
audio.style.display = 'none'; // 防止影響頁(yè)面布局
audio.controls = true;
document.body.appendChild(audio);
audio.src = wavFile;
audio.playbackRate = 1.3;
audio.play();
// 語(yǔ)音播放完畢后,需要手動(dòng)釋放內(nèi)存
audio.onended = function () {
document.body.removeChild(audio);
};
};
感謝
后端返回二進(jìn)制流音頻數(shù)據(jù),怎么讓其可播放
前端播放二進(jìn)制語(yǔ)音流文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-768648.html
到了這里,關(guān)于【JavaScript】后端返回的二進(jìn)制流音頻數(shù)據(jù)或本地音頻資源,前端如何播放?的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!