speech.vue 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <template>
  2. <view>
  3. <page-head :title="title"></page-head>
  4. <view class="uni-padding-wrap uni-common-mt">
  5. <view class="uni-textarea">
  6. <textarea :value="value" placeholder="语音识别内容展示区域" disabled />
  7. </view>
  8. <view class="uni-common-mt uni-btn-v">
  9. <button type="primary" @tap="startRecognize">开始语音识别</button>
  10. <!-- <button type="primary" @tap="startRecognizeEnglish">开始语音识别(英语)</button> -->
  11. </view>
  12. </view>
  13. </view>
  14. </template>
  15. <script>
  16. import permision from "@/common/permission.js"
  17. export default {
  18. data() {
  19. return {
  20. title: 'speech',
  21. value: ''
  22. }
  23. },
  24. onUnload(){
  25. this.value = ""
  26. },
  27. methods: {
  28. async startRecognize () {
  29. // #ifdef APP-PLUS
  30. let status = await this.checkPermission();
  31. if (status !== 1) {
  32. return;
  33. }
  34. // #endif
  35. // TODO ios 在没有请求过权限之前无法得知是否有相关权限,这种状态下需要直接调用语音,会弹出正在识别的toast
  36. var options = {};
  37. var that = this;
  38. options.engine = 'baidu';
  39. that.value = "";
  40. plus.speech.startRecognize(options, function (s) {
  41. console.log(s);
  42. that.value += s;
  43. }, function (e) {
  44. console.log("语音识别失败:" + e.message);
  45. });
  46. },
  47. async startRecognizeEnglish () {
  48. // #ifdef APP-PLUS
  49. let status = await this.checkPermission();
  50. if (status !== 1) {
  51. return;
  52. }
  53. // #endif
  54. // TODO ios 在没有请求过权限之前无法得知是否有相关权限,这种状态下需要直接调用语音,会弹出正在识别的toast
  55. var options = {};
  56. var that = this;
  57. options.engine = 'baidu';
  58. options.lang = 'en-us';
  59. that.value = "";
  60. plus.speech.startRecognize(options, function (s) {
  61. console.log(s);
  62. that.value += s;
  63. }, function (e) {
  64. console.log("语音识别失败:" + e.message);
  65. });
  66. }
  67. // #ifdef APP-PLUS
  68. ,
  69. async checkPermission() {
  70. let status = permision.isIOS ? await permision.requestIOS('record') :
  71. await permision.requestAndroid('android.permission.RECORD_AUDIO');
  72. if (status === null || status === 1) {
  73. status = 1;
  74. } else if (status === 2) {
  75. uni.showModal({
  76. content: "系统麦克风已关闭",
  77. confirmText: "确定",
  78. showCancel: false,
  79. success: function(res) {
  80. }
  81. })
  82. } else {
  83. uni.showModal({
  84. content: "需要麦克风权限",
  85. confirmText: "设置",
  86. success: function(res) {
  87. if (res.confirm) {
  88. permision.gotoAppSetting();
  89. }
  90. }
  91. })
  92. }
  93. return status;
  94. }
  95. // #endif
  96. }
  97. }
  98. </script>
  99. <style>
  100. </style>