# Google TTS API 使用 google目前把TTS納入收費模式 這個api還可以使用,但是不確定google哪時候會把這個api關閉 http://translate.google.com/translate_tts?ie=UTF-8&total=1&idx=0&textlen=32&client=tw-ob&q=%E5%B7%B2%E7%B6%93%E5%B9%AB%E4%BD%A0%E6%89%93%E9%96%8B%E9%9B%BB%E7%87%88&tl=zh-cn ## 串接google cloud api 服務憑證一直失敗,找不到解決原因,最後用api金鑰的方式串接 ## POST 的方式送出http api google tts api ``` https://texttospeech.googleapis.com/v1/text:synthesize?key={your_api_key} ``` json格式送出內容 ``` { "voice":{ "languageCode":"en-US" }, "input":{ "text":"Hello world" }, "audioConfig":{ "audioEncoding":"mp3" } } ``` 會回傳base64編碼後的String ``` { "audioContent": string } ``` 最後解碼後回傳byte[]的形態 ``` response.setContentType("audio/mpeg"); ``` ## 網頁上可以用html audio 的方式播放出聲音 先將base64編碼後的String 轉換成 blob 格式 再放到audio 的 src 範例: ``` let audioBlob = base64ToBlob(response.data.audioContent, "mp3"); audio_success.src = window.URL.createObjectURL(audioBlob); audio_success.playbackRate = 1; audio_success.play(); function base64ToBlob(base64, fileType) { let typeHeader = "data:application/" + fileType + ";base64,"; // 定义base64 头部文件类型 let audioSrc = typeHeader + base64; // 拼接最终的base64 let arr = audioSrc.split(","); let array = arr[0].match(/:(.*?);/); let mime = (array && array.length > 1 ? array[1] : type) || type; // 去掉url的头,并转化为byte let bytes = window.atob(arr[1]); // 处理异常,将ascii码小于0的转换为大于0 let ab = new ArrayBuffer(bytes.length); // 生成视图(直接针对内存):8位无符号整数,长度1个字节 let ia = new Uint8Array(ab); for (let i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab], { type: mime }); } ```
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.