【微信小程序】接入微软azure文本转语音的记录

前言

想在微信小程序中实现文本转语音的功能,使用azure的RESTful API。
先说结论:还是在后台处理吧
现象:模拟器上运行是正常的,可以获得转换后的音频,真机调试时,statusCode:400,在官方文档中的解释是,参数错误,常见原因是:标头过长。
原因:小程序wx.request user-agent过长了,超过了azure官方文档API里的限制:255个字符。
小程序wx.request user-agent过长怎么解决?
解决方法:小程序请求自己后端,自己后端再请求第三方接口

所以正文只是想记录一下调用接口&实现的过程,万一哪天官方把这个限制改了呢~(如果是用在网站上的话,过程应该也差不多吧)

正文

首先,注册账号巴拉巴拉不提(因为不是我注册的0 0)好像是需要国外信用卡之类的?
将可以获得:
1.subscriptionKey,订阅密钥
2.区域信息,一般国内就是eastasia了。

使用过程:

1.获取subscriptionKey

因为subscriptionKey放后台了,所以前端使用的时候需要获取一下。

  getAzureKey() {
    
    
    request.get('xxxx').then(res => {
    
    
      if (res.data.code == '200') {
    
    
        this.setData({
    
    
          subscriptionKey: res.data.result.subscriptionKey
        })
      } else {
    
    
        console.log('something error')
      }
    })
  },

2.开始获取语音

  getAudio(e) {
    
    
    let text ='你好!' //想要转换的文本
    let that = this
    //先获得token
    wx.request({
    
    
      url: 'https://eastasia.api.cognitive.microsoft.com/sts/v1.0/issueToken',
      method: 'POST',
      header: {
    
    
        'Ocp-Apim-Subscription-Key': that.data.subscriptionKey
      },
      success(res) {
    
    
        const token = res.data
        //开始转换
        wx.request({
    
    
          url: 'https://eastasia.tts.speech.microsoft.com/cognitiveservices/v1',
          method: 'POST',
          data: `<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='zh-CN'><voice name='zh-CN-XiaoqiuNeural'>${
      
      text}</voice></speak>`,
          header: {
    
    
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/ssml+xml',
            'X-Microsoft-OutputFormat': 'audio-16khz-128kbitrate-mono-mp3',
          },
          responseType: "arraybuffer", //注意要转换成arraybuffer的
          success: function (result) {
    
    
            console.log(result)
            if (result.statusCode == '200') {
    
    
              console.log('ok')
              const fs = wx.getFileSystemManager();
              const filePath = wx.env.USER_DATA_PATH + "/output.mp3";
              fs.writeFileSync(filePath, result.data, "binary");//写入
              that.setData({
    
    
                audioSrc: filePath,
              });
              //音频播放
              const audio = wx.createInnerAudioContext();
              audio.src = filePath;
              audio.play();
              audio.onEnded(() => {
    
    
                console.log("Voice playback complete.");
              });
            } else {
    
    
              console.log(result)
            }
          }
        })
      },
      fail() {
    
    
        console.log('获取token失败')
      }
    })

  },

完成。

后端正在写接口Ing,后续待补充。。。

猜你喜欢

转载自blog.csdn.net/sinat_41838682/article/details/130045106