TTS (文本生成语音)
在算力舱中部署了一个 Kokoro 的 tts 服务,这个服务的速度比较快。
在线演示
您可以通过 访问在线演示。
文档
tts 服务的 api 可以通过 查看。
示例
vue
<template>
<div class="tts-player">
<div class="input-section">
<textarea
v-model="text"
placeholder="请输入要转换的文本..."
class="text-input"
rows="4"
></textarea>
<button
@click="synthesizeSpeech"
:disabled="isLoading"
class="synthesize-btn"
>
{{ isLoading ? "转换中..." : "转换为语音" }}
</button>
</div>
<div class="player-section" v-if="audioUrl">
<audio
ref="audioPlayer"
:src="audioUrl"
controls
class="audio-player"
></audio>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
const text = ref("欢迎使用算力舱,玩的开心。welcome use AI pod, happy hack!");
const audioUrl = ref("");
const isLoading = ref(false);
const audioPlayer = ref(null);
const domain = () => {
const currentHost = window.location.host;
const host = currentHost.replace(/^([^.]+)/, "tts-ai");
const protocol = window.location.protocol;
return `${protocol}//${host}`;
};
const synthesizeSpeech = async () => {
if (!text.value.trim()) {
alert("请输入要转换的文本");
return;
}
isLoading.value = true;
try {
const response = await fetch(`${domain()}/v1/audio/speech`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
input: text.value,
voice: "zf_044",
response_format: "mp3",
download_format: "wav",
stream: true,
speed: 1,
return_download_link: true,
}),
});
if (!response.ok) {
throw new Error("语音合成请求失败");
}
const blob = await response.blob();
audioUrl.value = URL.createObjectURL(blob);
// 自动播放
if (audioPlayer.value) {
audioPlayer.value.play();
}
} catch (error) {
console.error("语音合成错误:", error);
alert("语音合成失败,请重试");
} finally {
isLoading.value = false;
}
};
</script>
<style>
.tts-player {
margin: 0 auto;
}
.input-section {
margin-bottom: 20px;
}
.text-input {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 10px;
font-size: 16px;
resize: vertical;
}
.synthesize-btn {
background-color: #4caf50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
}
.synthesize-btn:hover {
background-color: #45a049;
}
.synthesize-btn:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.player-section {
margin-top: 20px;
}
.audio-player {
width: 100%;
}
</style>