功能介绍:
请求语音合成服务,通过上传语音合成文本,返回音频数据,并保存到本地。这里要说明一下,由于HttpResponse
接口给问题,服务的响应类型必须是application/octet-stream
,才能正确获取音频数据并保存,接口文档:HttpResponse。
语音合成服务可以参考:轻松快速搭建一个本地的语音合成服务
使用环境:
所需权限:
注意: 只适合小于5M数据。
关键代码片段如下:
async download() {
if (this.text == "")return
promptAction.showToast({ message: "合成文本:" + this.text })
let httpRequest = http.createHttp();
let context = getContext(this) as common.UIAbilityContext;
const filesDir = context.filesDir;
let promise = httpRequest.request(this.ttsUrl, {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json; charset=utf-8' },
extraData: { "text": this.text }
})
promise.then((data) => {
const timestamp = Date.now();
const savePath = filesDir + `/${timestamp}.wav`
console.info("保存路径:" + savePath)
let file = fs.openSync(savePath, fs.OpenMode.WRITE_ONLY | fs.OpenMode.CREATE);
// @ts-ignore
fs.write(file.fd, data.result).then((writeLen) => {
fs.closeSync(file);
console.info("已成功保存文件,文件大小为:" + writeLen);
}).catch((err) => {
console.error("保存文件出错,错误信息:" + err.message + ", 错误代码:" + err.code);
});
}).catch((err) => {
console.error('错误信息:' + JSON.stringify(err))
})
}
完整代码:
import promptAction from '@ohos.promptAction';
import http from '@ohos.net.http';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
@Entry
@Component
struct Index {
@State text: string = ''
@State ttsUrl: string = "http://xxxx.xxxx"
build() {
Row() {
TextInput({ placeholder: '请输入要合成的语音文本' })
.width("70%")
.height(40)
.onChange((value: string) => {
this.text = value
})
Button("合成")
.fontSize(16)
.width("25%")
.height(40)
.margin({ left: 10 })
.onClick(() => {
this.download()
})
}
.height("100%")
.padding({ bottom: 10 })
.alignItems(VerticalAlign.Bottom)
}
async download() {
if (this.text == "")return
promptAction.showToast({ message: "合成文本:" + this.text })
let httpRequest = http.createHttp();
let context = getContext(this) as common.UIAbilityContext;
const filesDir = context.filesDir;
let promise = httpRequest.request(this.ttsUrl, {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json; charset=utf-8' },
extraData: { "text": this.text }
})
promise.then((data) => {
const timestamp = Date.now();
const savePath = filesDir + `/${timestamp}.wav`
console.info("保存路径:" + savePath)
let file = fs.openSync(savePath, fs.OpenMode.WRITE_ONLY | fs.OpenMode.CREATE);
// @ts-ignore
fs.write(file.fd, data.result).then((writeLen) => {
fs.closeSync(file);
console.info("已成功保存文件,文件大小为:" + writeLen);
}).catch((err) => {
console.error("保存文件出错,错误信息:" + err.message + ", 错误代码:" + err.code);
});
}).catch((err) => {
console.error('错误信息:' + JSON.stringify(err))
})
}
}