功能介紹:

請求語音合成服務,通過上傳語音合成文本,返回音頻數據,並保存到本地。這裏要說明一下,由於HttpResponse接口給問題,服務的響應類型必須是application/octet-stream,才能正確獲取音頻數據並保存,接口文檔:HttpResponse

語音合成服務可以參考:輕鬆快速搭建一個本地的語音合成服務

使用環境:

  • API 9
  • DevEco Studio 4.0 Release
  • Windows 11
  • Stage模型
  • ArkTS語言

所需權限:

  1. ohos.permission.INTERNET
  2. 只保存在應用文件夾,不涉及額外目錄,不需要申請讀寫權限

注意: 只適合小於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 = ''
  private 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))
    })
  }
}
小夜