播放ReadableStream格式二进制流音频
接口返回中,body为
ReadableStream
格式的二进制流
<!DOCTYPE html>
<html>
<head>
<title>实时语音生成与播放</title>
</head>
<body>
<h1>输入文本生成语音</h1>
<textarea id="text-input" rows="4" cols="50"></textarea><br />
<button onclick="generateAndPlayAudio()">生成并播放语音</button>
<audio id="audio" controls></audio>
<script>
async function generateAndPlayAudio() {
const text = document.getElementById("text-input").value;
fetch("http://xxx.xx.xx.xxx:5000/generate_speech", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ text: text, port: 9880 }),
})
.then((response) => {
console.log("response", response);
if (response.ok) {
const reader = response.body.getReader();
let chunks = [];
let totalLength = 0;
const read = () => {
return reader.read().then(({ done, value }) => {
if (done) {
return new Blob(chunks, { type: "audio/wav" });
}
chunks.push(value);
totalLength += value.length;
return read();
});
};
return read();
}
})
.then((audioBlob) => {
const audioUrl = URL.createObjectURL(audioBlob);
console.log("Audio URL:", audioUrl);
const audioPlayer = document.getElementById("audio");
audioPlayer.src = audioUrl;
audioPlayer.play().catch((error) => {
console.error("Error playing audio:", error);
});
});
}
</script>
</body>
</html>