1.vue 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <template>
  2. <view>
  3. <button @tap="startRecord">开始录音</button>
  4. <button @tap="endRecord">停止录音</button>
  5. <button @tap="playVoice">播放录音</button>
  6. <button @tap="startRecognize">开始识别</button>
  7. </view>
  8. </template>
  9. <script>
  10. const recorderManager = uni.getRecorderManager();
  11. const innerAudioContext = uni.createInnerAudioContext();
  12. innerAudioContext.autoplay = true;
  13. var _this;
  14. export default {
  15. data(){
  16. return {
  17. voicePath : ''
  18. }
  19. },
  20. onLoad() {
  21. _this = this;
  22. recorderManager.onStop(function(res) {
  23. console.log(res)
  24. _this.voicePath = res.tempFilePath
  25. // 使用uni.uploadFile上传到服务器上,此时是mp3格式
  26. });
  27. },
  28. methods: {
  29. startRecord() {
  30. console.log('开始录音');
  31. recorderManager.start({
  32. sampleRate: 16000 // 必须设置是后台设置的参数,不然百度语音识别不了
  33. });
  34. },
  35. endRecord() {
  36. console.log('录音结束');
  37. _this = this;
  38. recorderManager.stop();
  39. },
  40. playVoice() {
  41. console.log('播放录音');
  42. if (this.voicePath) {
  43. innerAudioContext.src = this.voicePath;
  44. innerAudioContext.play();
  45. }
  46. },
  47. startRecognize() {
  48. var options = {};
  49. options.engine = 'baidu';
  50. console.log("开始语音识别:");
  51. plus.speech.startRecognize(options, function(s){
  52. console.log("识别结果:"+s)
  53. plus.speech.stopRecognize();
  54. }, function(e){
  55. console.log("语音识别失败:"+e.message);
  56. });
  57. }
  58. }
  59. }
  60. </script>