123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265 |
- <template>
- <view>
- <view class="VoiceModel" v-show="VoiceModel">
- <view class="container" @touchstart="startRecord" @touchend="endRecord">
- <text class="zhcx-iconfont zhcx-icon-yuyin"></text>
- <view class="status">{{status}}</view>
- </view>
- </view>
- </view>
- </template>
- <script>
- import {notEmpty} from '@/libs';
- import config from '@/config';
- const speechConfig=config.baidu.speech;
- const speechAppId=speechConfig.appId;
- const speechApiKey=speechConfig.apiKey;
- const speechSecretKey=speechConfig.secretKey;
-
- const recorderManager = uni.getRecorderManager();
- const innerAudioContext = uni.createInnerAudioContext();
- innerAudioContext.autoplay = true;
- export default {
- name:'speech-baidu',
- data() {
- return {
- text: 'uni-app',
- voicePath: '',
- fileSize:0,
- word:"",
- VoiceModel:false,
- status:"长按开始录音"
- }
- },
- created() {
- this.$nextTick(()=>{
- recorderManager.onStop(res=>{
- console.log('recorder stop' + JSON.stringify(res));
- uni.showToast({
- title:"录音结束!"
- })
- this.status="录音结束";
- this.voicePath = res.tempFilePath;
- this.fileSize=res.fileSize;
- this.startYuyin();
- });
- })
- },
- methods: {
- startRecordHanlle(){
- this.VoiceModel=true;
- },
- startRecord() {
- this.status="开始录音";
- recorderManager.start();
- setTimeout(()=>{
- this.endRecord()
- },60000)
- },
- endRecord() {
- console.log('录音结束')
- // #ifdef H5
-
- return;
- // #endif
- this.status="录音结束";
- recorderManager.stop();
- setTimeout(()=>{
- this.VoiceModel=false;
- },600)
- },
- playVoice() {
- console.log('播放录音');
- if (this.voicePath) {
- innerAudioContext.src = this.voicePath;
- innerAudioContext.play();
- }
- },
- async startYuyin() {
- console.log('识别中……')
- uni.showLoading({
- title: '识别中……'
- });
- let adioFileData=await this.Audio2dataURL(this.voicePath);
- let {access_token}=await this.getToken();
- let result=await this.ConversionWords({
- format: 'm4a', //语音文件的格式,pcm/wav/amr/m4a。不区分大小写。推荐pcm文件
- rate: 16000, // 采样率,16000,固定值 此处文档参数16000,达不到这种高保真音频,故 使用8000
- // dev_pid: 1537,//普通话
- channel: 1, //声道数,仅支持单声道,请填写固定值 1
- cuid: 'zhcxcuid', //用户唯一标识,用来区分用户,计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内。
- token:access_token,
- speech:adioFileData, //本地语音文件的的二进制语音数据 ,需要进行base64 编码。与len参数连一起使用。
- len: this.fileSize //本地语音文件的的字节数,单位字节 init
- })
-
- if(result.statusCode===200){
- let word=result.data.result[0];
- if(notEmpty(word)){
- this.$emit('success',result)
- }else{
- uni.showToast({
- icon:"none",
- title:"未识别到文字!"
- })
- this.status="未识别到文字";
- }
- }else{
- uni.showToast({
- icon:"none",
- title:"语音识别失败"
- })
- this.status="语音识别失败";
- }
- },
- getToken(){
- return new Promise((resolve,reject)=>{
- //获取token
- uni.request({
- url: 'https://openapi.baidu.com/oauth/2.0/token', //仅为示例,并非真实接口地址。
- data: {
- grant_type: 'client_credentials',
- client_id: speechApiKey,
- client_secret:speechSecretKey,
- },
- header: {
- 'content-type': 'application/json;charset=utf-8' //自定义请求头信息
- },
- success: (res) => {
- resolve(res.data)
- },
- fail(err) {
- uni.showToast({
- icon:"none",
- title:"语音识别失败"
- })
- this.status="语音识别失败";
- uni.hideLoading();
- reject(err)
- }
- });
- })
- },
- ConversionWords(postData) {
- //调用语音识别接口
- return new Promise((resolve,reject)=>{
- uni.request({
- url: 'https://vop.baidu.com/server_api', //仅为示例,并非真实接口地址。
- data: postData,
- header: {
- "Content-Type":"application/json" //自定义请求头信息
- },
- method: 'POST',
- success: (res) => {
- resolve(res)
- },
- fail(err) {
- uni.showToast({
- icon:"none",
- title:"语音识别失败"
- })
- this.status="语音识别失败";
- reject(err)
- },
- complete() {
- uni.hideLoading();
- }
- })
- })
- },
- Audio2dataURL(path) {
- return new Promise((resolve,reject)=>{
- const FMS = uni.getFileSystemManager();
- FMS.readFile({
- filePath:this.voicePath,
- encoding: 'base64',
- success(response) {
- resolve(response.data)
- },
- fail(err){
- uni.showToast({
- icon:"none",
- title:"语音识别失败"
- })
- this.status="语音识别失败";
- uni.hideLoading();
- reject(err)
- }
- })
- // plus.io.resolveLocalFileSystemURL(path, function(entry) {
- // entry.file(function(file) {
- // var reader = new plus.io.FileReader();
- // _this.adioSize = file.size;
- // reader.onloadend = function(e) {
- // console.log(e.target.result);
- // console.log(e.target.result.split(",")[1]);
- // resolve({
- // voice:e.target.result.split(",")[1]
- // })
- // };
- // reader.readAsDataURL(file);
- // }, function(e) {
- // reject(e.message)
- // console.log("读写出现异常: " + e.message);
- // })
- // })
- })
- }
- }
- }
- </script>
- <style lang="scss" scoped>
- .word-cont{
- height: 200upx;
- overflow-y: auto;
- border-bottom:1px solid #ccc;
- }
- .startRecordHanlle{
- width:280upx;
- margin: 100upx auto;
- background-color: #0081ff;
- color: #fff;
- .zhcx-icon-yuyin{
- font-size: 46upx;
- padding-right: 10upx;
- }
- }
- .VoiceModel{
- width: 100%;
- height: 100%;
- position: fixed;
- left: 0;
- top: 0;
- background-color: rgba(0,0,0,0.6);
- z-index: 999;
- .container{
- width: 240upx;
- height: 320upx;
- border-radius: 10upx;
- background-color:#fff;
- box-shadow:0 0 2upx rgba(0,0,0,0.6);
- position: fixed;
- left: 50%;
- top:280upx;
- transform: translateX(-50%);
- z-index: 999;
- text-align: center;
- display: flex;
- justify-content: space-between;
- align-items: center;
- flex-direction: column;
- .zhcx-icon-yuyin{
- color: #17b18f;
- font-size: 200upx;
- }
- .status{
- color:#17b18f;
- padding-bottom: 10upx;
- }
- }
- }
- </style>
|