uni-app中使用

小程序中使用

  • app.json

    1. "plugins": {
    2. "WechatSI": {
    3. "version": "0.3.3",//版本号
    4. "provider": "wx069ba97219f66d99" // 插件id
    5. }
    6. }
  • 页面中

    1. <view class="yuyinWrap">
    2. <textarea class='yuyinCon' placeholder='请输入内容' value='{{content}}' bindinput='conInput'></textarea>
    3. <view class=''>
    4. <button class="yuyinBtn start" bindtap='wordYun'>开始</button>
    5. <button class="yuyinBtn" bindtap='end'>结束</button>
    6. </view>
    7. </view>
  • js内容 ```javascript const app = getApp(); //引入插件:微信同声传译 const plugin = requirePlugin(‘WechatSI’);

Page({ /**

  1. * 页面的初始数据
  2. */
  3. data: {
  4. content: '一、南阳世界月季大观园一期(东园、中园、北园)', //内容
  5. src: '', //
  6. },
  7. onReady(e) {
  8. this.innerAudioContext = wx.createInnerAudioContext();
  9. this.innerAudioContext.autoplay = true;
  10. },
  11. // 手动输入内容
  12. conInput: function(e) {
  13. this.setData({
  14. content: e.detail.value,
  15. })
  16. },
  17. // 文字转语音
  18. wordYun: function(e) {
  19. var that = this;
  20. var content = this.data.content;
  21. plugin.textToSpeech({
  22. lang: "zh_CN",
  23. tts: true,
  24. content: content.slice(0, 500),
  25. success: function(res) {
  26. console.log(res);
  27. console.log("succ tts", res.filename);
  28. that.setData({
  29. src: res.filename
  30. })
  31. that.yuyinPlay();
  32. },
  33. fail: function(res) {
  34. console.log("fail tts", res)
  35. }
  36. })
  37. },
  38. //播放语音
  39. yuyinPlay(e) {
  40. if (this.data.src == '') {
  41. console.log(暂无语音);
  42. return;
  43. }
  44. console.log(this.data.src);
  45. this.innerAudioContext.src = this.data.src //设置音频地址
  46. this.innerAudioContext.play(); //播放音频
  47. this.innerAudioContext.onStop(() => {
  48. console.log('i am onStop');
  49. innerAudioContext.stop();
  50. //播放停止,销毁该实例
  51. this.innerAudioContext.destroy();
  52. })
  53. this.innerAudioContext.onPlay(() => {
  54. console.log("正在播放")
  55. })
  56. this.innerAudioContext.onEnded(() => {
  57. console.log('i am onEnded');
  58. //播放结束,销毁该实例
  59. this.innerAudioContext.destroy();
  60. console.log('已执行destory()');
  61. })
  62. this.innerAudioContext.onError((res) => {
  63. /* console.log(res.errMsg);
  64. console.log(res.errCode); */
  65. this.innerAudioContext.destroy();
  66. })
  67. },
  68. // 结束语音
  69. end: function(e) {
  70. console.log("结束语音")
  71. this.innerAudioContext.pause(); //暂停音频
  72. },

})

```

注意事项

字数限制

官网上说内容限制为1000字节,也就是说可以输入将近500中文,但实际测试后发现350个文字会报错,330个文字可能会报错,320个字稳定不报错 text to speech inner server failed