vue 使用Google Cloud Text-to-Speech
时间: 2025-02-21 17:25:33 浏览: 51
### 集成 Google Cloud Text-to-Speech API 到 Vue 项目
为了在 Vue.js 中集成并使用 Google Cloud Text-to-Speech API 来实现文本转语音功能,需遵循以下指南:
#### 安装必要的依赖项
首先,在前端环境中安装 `google-cloud/text-to-speech` 库并不合适,因为这涉及到敏感的服务账户密钥暴露风险。因此建议创建一个后端服务器来处理与 Google Cloud 的交互。
对于 Node.js 后端环境来说,可以通过 npm 或 yarn 添加 google cloud sdk:
```bash
npm install --save @google-cloud/text-to-speech
```
或者
```bash
yarn add @google-cloud/text-to-speech
```
#### 创建后端接口用于调用 TTS API
定义一个简单的 Express 路由作为中介层,接收来自前端的请求并将结果返回给客户端[^1]:
```javascript
// server.js or app.js depending on your setup
const express = require('express');
const {TextToSpeechClient} = require('@google-cloud/text-to-speech');
app.post('/api/tts', async (req, res) => {
const client = new TextToSpeechClient();
// Construct the request object with input text and voice settings.
const [response] = await client.synthesizeSpeech({
input: {text: req.body.text},
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
audioConfig: {audioEncoding: 'MP3'}
});
// Send back synthesized speech as binary data.
res.set({'Content-Type': 'audio/mpeg'});
res.send(response.audioContent);
});
```
此代码片段展示了如何设置 POST 请求处理器 `/api/tts` ,该处理器接受 JSON 格式的 body 参数 `{ "text": string }` 并响应 MP3 编码的声音文件流。
#### 前端部分:发送 AJAX 请求获取音频数据
接下来是在 Vue 组件内部发起 HTTP 请求的方式之一——使用 axios 发送异步 GET/POST 请求至上述自建API路径,并播放接收到的数据。
```html
<template>
<div id="tts-app">
<input v-model="message" placeholder="Enter some text here"/>
<button @click="speak()">Speak</button>
<!-- Audio element to play returned sound -->
<audio ref="player"></audio>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'TtsApp',
data() {
return {
message: ''
}
},
methods: {
speak(){
let self = this;
axios.post("/api/tts", {"text":this.message})
.then(function(response){
// Create a Blob out of response array buffer
var blob = new Blob([new Uint8Array(response.data)], {'type':'audio/mp3'});
// Set src attribute of HTMLAudioElement instance
self.$refs.player.src = URL.createObjectURL(blob);
// Play it!
self.$refs.player.play().catch(console.error);
})
.catch(console.error);
}
}
}
</script>
```
这段模板和脚本实现了基本的文字输入框以及按钮点击事件触发器;当用户按下 Speak 按钮时会向后台提交待合成的内容字符串并通过 `<audio>` DOM 元素自动回放生成的结果。
阅读全文
相关推荐














