语音修改

This commit is contained in:
jia 2023-10-18 18:30:07 +08:00
parent e7b7551a2e
commit d1f6af0aee
2 changed files with 242 additions and 539 deletions

View File

@ -1,6 +1,6 @@
{ {
"name" : "农业咨询", "name" : "农业咨询",
"appid" : "__UNI__3A527D1", "appid" : "__UNI__9620511",
"description" : "", "description" : "",
"versionName" : "1.0.0", "versionName" : "1.0.0",
"versionCode" : "100", "versionCode" : "100",
@ -17,11 +17,7 @@
"delay" : 0 "delay" : 0
}, },
/* */ /* */
"modules" : { "modules" : {},
"Record" : {},
"Speech" : {},
"Camera" : {}
},
/* */ /* */
"distribute" : { "distribute" : {
/* android */ /* android */
@ -51,9 +47,7 @@
}, },
/* SDK */ /* SDK */
"sdkConfigs" : { "sdkConfigs" : {
"ad" : {}, "ad" : {}
"speech" : {},
"share" : {}
} }
} }
}, },
@ -61,7 +55,7 @@
"quickapp" : {}, "quickapp" : {},
/* */ /* */
"mp-weixin" : { "mp-weixin" : {
"appid" : "wx3267f87bc81f2890", "appid" : "",
"setting" : { "setting" : {
"urlCheck" : false "urlCheck" : false
}, },

View File

@ -60,10 +60,10 @@
</view> </view>
<view class="contenta" v-if="c_content!=''&&index==nums"> <view class="contenta" v-if="c_content!=''&&index==nums">
<view class="contenta-img" v-if='palystatus' @click="palyaudio(item)"> <view class="contenta-img" v-if='palystatus' @click="palyaudio(item,index)">
<image src="@/static/icon/ai7.png" mode="aspectFit"></image> <image src="@/static/icon/ai7.png" mode="aspectFit"></image>
</view> </view>
<view class="contenta-img" v-else @click="palyaudio(item)"> <view class="contenta-img" v-else @click="palyaudio(item,index)">
<image src="@/static/icon/ai8.png" mode="aspectFit"></image> <image src="@/static/icon/ai8.png" mode="aspectFit"></image>
</view> </view>
<view class="contenta-ai" v-show="palystatus==false"> <view class="contenta-ai" v-show="palystatus==false">
@ -112,8 +112,7 @@
</view> </view>
<view class="flex_c_txt" v-else> <view class="flex_c_txt" v-else>
<view class="con" @touchend="end" @touchmove="move" @touchstart="start" @longpress="longpress" <view class="con" @touchend="end" @touchmove="move" @touchstart="start">
@click="longclick">
{{btnStatus==0? "按住说话":btnStatus==1? "说话中...": btnStatus==2? "松开手指发送录音": "上划取消"}} {{btnStatus==0? "按住说话":btnStatus==1? "说话中...": btnStatus==2? "松开手指发送录音": "上划取消"}}
</view> </view>
<!-- <view :class=" btnStatus==0? 'footerBtn': btnStatus==1?'footerBtn_star':'footerBtn_move'"> <!-- <view :class=" btnStatus==0? 'footerBtn': btnStatus==1?'footerBtn_star':'footerBtn_move'">
@ -184,7 +183,6 @@
</uni-popup> </uni-popup>
<qiqbshare ref="child"></qiqbshare> <qiqbshare ref="child"></qiqbshare>
</view> </view>
</template> </template>
@ -194,7 +192,9 @@
iatWss, iatWss,
debounce, debounce,
throttle, throttle,
ttWss fileToBase64,
dataURLtoBlob,
ttWss,
} from "@/api/api.js" } from "@/api/api.js"
import { import {
HTTP_REQUEST_URL HTTP_REQUEST_URL
@ -212,9 +212,8 @@
import BingMath from "@/components/bing-math/bing-math.vue" import BingMath from "@/components/bing-math/bing-math.vue"
import qiqbshare from "@/components/qiqb-share/qiqb-share.vue" import qiqbshare from "@/components/qiqb-share/qiqb-share.vue"
// module
const sr = uni.requireNativePlugin("YL-SpeechRecognition")
const recorderManager = uni.getRecorderManager()
const innerAudioContext = uni.createInnerAudioContext() const innerAudioContext = uni.createInnerAudioContext()
export default { export default {
@ -273,16 +272,15 @@
touchMoveX: 0, // x touchMoveX: 0, // x
touchMoveY: 0, // y touchMoveY: 0, // y
risshow: false, risshow: false,
touchT: null,
touchE: null,
islong: false, islong: false,
// //
isDraw: false, isDraw: false,
imageSize: { imageSize: {
} },
audio_file: [],
currentIndex: 0,
wv: null
} }
}, },
mounted() { mounted() {
@ -302,7 +300,20 @@
}) })
}) })
//
sr.init("2eda6c2e");
//
sr.createTts(code => {});
//
sr.createIat(code => {
console.log(code, '1111111111')
});
sr.setVadBos(10 * 1000); //ms10s,
sr.setVadEos(10 * 1000); //ms10s,
},
beforeDestroy() {
sr.destroy();
}, },
onLoad() { onLoad() {
let avatar = uni.getStorageSync('avatar'); let avatar = uni.getStorageSync('avatar');
@ -311,6 +322,9 @@
this.avatar = e.avatar; this.avatar = e.avatar;
}) })
}, },
beforeDestroy() { beforeDestroy() {
// #ifdef APP-PLUS // #ifdef APP-PLUS
@ -322,24 +336,7 @@
this.getHistoryMsg(); this.getHistoryMsg();
} }
}, },
created() {
//
// uni.setInnerAudioOption({
// obeyMuteSwitch: false
// })
let that = this;
recorderManager.onStop(function(res) {
// ,
that.$nextTick(() => {
// console.log('recorder stop' + JSON.stringify(res));
that.audioDuration = res.duration;
that.voicePath = res.tempFilePath;
})
});
this.list()
},
watch: { watch: {
n_content(n, o) { n_content(n, o) {
@ -373,6 +370,7 @@
methods: { methods: {
//
cavshare(data) { cavshare(data) {
let arry = [] let arry = []
@ -524,12 +522,7 @@
}) })
}, },
//
list() {
iatWss().then((res) => {
this.audioUrl = res.data.iat_wss
})
},
// //
addgn() { addgn() {
@ -541,69 +534,7 @@
this.$refs.popup.close() this.$refs.popup.close()
}, },
//
uploadFile(tempFilePath) {
let that = this
// console.log(tempFilePath)
uni.uploadFile({
url: HTTP_REQUEST_URL + '/api/xun_fei/iat', //
filePath: tempFilePath, //
name: 'audio', // key
header: {
'content-type': 'multipart/form-data'
},
success: function(res) {
// console.log(res)
let data = JSON.parse(res.data)
if (data.code == 1) {
uni.showToast({
title: '语音识别成功'
});
that.talkList = that.talkList.filter(item => item.id !== '@');
if (data.data.words.length > 0) {
that.content = data.data.words
that.send1()
}
// console.log( that.talkList)
// if (that.talkList.length > 0) {
// that.talkList.splice(that.talkList.length - 1, 1)
// } else {
// that.talkList.splice(0, 1)
// }
that.voicePath = ''
// if (that.content.length > 0) {
// that.send()
// }
} else {
that.talkList = that.talkList.filter(item => item.id !== '@');
uni.showToast({
title: '语音识别失败'
});
}
},
fail: function(error) {
//
that.deletespeech()
console.log(error, 11);
uni.hideLoading();
}
})
},
// //
onFeedTap() { onFeedTap() {
let platform = uni.getSystemInfoSync().platform let platform = uni.getSystemInfoSync().platform
@ -628,169 +559,174 @@
} }
// #endif // #endif
}, },
// //
txtspeech(val, i) { txtspeech(val, i) {
// xuiat({ xuiat({
// text: val text: val
// }).then(res => {
// if (res.code == 1) {
// this.talkList[i].audio_file = res.data.audio_file
// this.nums = this.talkList.length - 1
// // this.palyaudio(res.data)
// }
// }).catch((err) => {
// console.log(err)
// })
ttWss({
data: val
}).then(res => { }).then(res => {
if (res.code == 0) { if (res.code == 1) {
this.talkList[i].audio_file = res.data.mp3 this.talkList[i].audio_file = res.data.audio_file
this.nums = this.talkList.length - 1
this.nums = this.talkList.length - 1 this.nums = this.talkList.length - 1
// this.palyaudio(res.data)
} }
}).catch((err) => { }).catch((err) => {
console.log(err) console.log(err)
}) })
//
// let arry1;
// if (val.indexOf(',') == -1) {
// arry1 = val.split(',')
// } else if (val.indexOf('') == -1) {
// arry1 = val.split('')
// } else {
// arry1.push(val)
// }
// const temp = []
// for (let i = 0; i < arry1.length; i++) {
// temp.push(
// // 使Promise
// new Promise((resolve, reject) => {
// ttWss({
// data: arry1[i]
// }).then(res => {
// return resolve(res.data.mp3)
// }).catch(err => {
// return reject(err)
// })
// })
// )
// }
// Promise.all(temp).then(res => {
// // console.log(res,'2222222')
// this.audio_file = res
// this.ScanAudio(res, this.currentIndex, 0)
// })
}, },
// //
longclick() { ScanAudio(urls, currentIndex, delayInSeconds) {
if (this.touchE - this.touchT < 1000) {
console.log('点击'); if (currentIndex >= urls.length) {
this.palystatus = true;
return false;
} }
}, const music = uni.createInnerAudioContext();
longpress(e) { music.src = urls[currentIndex];
// console.log(e.touches[0].pageX) console.log(urls[currentIndex])
this.onFeedTap()
this.touchT = new Date().getTime(); console.log('播放成功', this.palystatus)
this.islong = true if (this.palystatus) {
this.risshow = false this.palystatus = false
this.$refs.popup.open('center') music.play();
//
this.timer = setInterval(() => { } else {
this.num++
}, 1000) music.pause();
this.btnStatus = 1
recorderManager.start({ }
//5,
duration: 300000 music.onEnded(() => {
music.destroy();
setTimeout(() => {
this.ScanAudio(urls, currentIndex + 1, delayInSeconds);
}, delayInSeconds * 1000);
}); });
this.touchStartX = e.touches[0].pageX; //
this.touchStartY = e.touches[0].pageY; // },
//
voiceToText() {
let that = this;
sr.voiceToText(data => {
// console.log(JSON.stringify(data));
if (data.code == 1001) {
// that.toTextStatus = "..."
} else if (data.code == 1006) {
// this.toTextStatus = ""
//
// sr.getIatPath(path => {
// that.path = path;
// });
} else if (data.code == 1007) {
// this.toTextStatus = ""
} else if (data.code == 1008) {
// this.volume = data.msg;
} else if (data.code == 1009) { //
//islast
// this.transText = data.msg;
if (data.isLast) {
if (data.msg.length > 0 && this.risshow == false) {
this.content = data.msg
this.send()
} else {
this.content = ''
this.stopVoiceToText()
}
}
} else if (data.code == 1010) { //error
//data.msg
if (data.msg) {
this.transText = data.msg;
}
}
})
},
//
stopVoiceToText() {
//10071009 ios 1007 1006 1009 1010
sr.stopListening();
}, },
start(e) { start(e) {
// console.log(e.touches[0].pageX) // console.log(e.touches[0].pageX)
this.touchStartX = e.touches[0].pageX; // this.touchStartX = e.touches[0].pageX; //
this.touchStartY = e.touches[0].pageY; // this.touchStartY = e.touches[0].pageY; //
clearTimeout(this.timer); //
let that=this
this.timer = setTimeout(function() {
//
// alert("")
that.onFeedTap()
that.islong = true
that.risshow = false
that.$refs.popup.open('center')
that.btnStatus = 1
that.voiceToText()
}.bind(this), 1500);
}, },
end() { end() {
this.touchE = new Date().getTime();
if (this.islong) { if (this.islong) {
this.closePop() this.closePop()
// clearInterval(this.timer1)
// this.btnStatus = 0
// //
// innerAudioContext.stop()
// //,,,
// setTimeout(() => {
// let obj = {
// status: false,
// path: [{
// src: this.voicePath,
// switchStatus: false,
// soundTime: this.num
// }]
// }
// console.log(1111, this.voicePath)
// // if (this.voicePath.length > 0) {
// // uni.$u.throttle(this.uploadFile(this.voicePath), 500)
// // }
// this.num = 0
// // pathToBase64(this.voicePath)
// // .then(base64 => {
// // const arrayBuffer = new Uint8Array(base64)
// // const base1 = uni.arrayBufferToBase64(arrayBuffer)
// // let params = {
// // common: {
// // app_id: '2eda6c2e',
// // },
// // business: {
// // language: "zh_cn",
// // domain: "iat",
// // accent: "mandarin",
// // vad_eos: 5000,
// // dwa: "wpgs",
// // },
// // data: {
// // status: 2,
// // format: "audio/L16;rate=16000",
// // encoding: "raw",
// // audio: base64.split(',')[1]
// // },
// // };
// // this.audioTxt = JSON.stringify(params)
// // this.audiosckt()
// // })
// // .catch(error => {
// // console.error(error)
// // })
// // this.socketaudio.send(JSON.stringify(params))
// }, 500)
this.islong = false this.islong = false
clearInterval(this.timer) clearInterval(this.timer) //
this.btnStatus = 0 this.btnStatus = 0;
recorderManager.stop(); this.stopVoiceToText()
// console.log(this.voicePath, "888");
// this.closePop()
if (this.risshow == false && this.touchE - this.touchT > 3000) {
let data = {
"id": '@',
"content": '加载完毕',
"type": 2,
"pic": this.avatarType
}
this.talkList.push(data);
// ,,,
setTimeout(() => {
let obj = {
status: false,
path: [{
src: this.voicePath,
switchStatus: false,
soundTime: this.num
}]
}
if (this.voicePath.length > 0 && this.risshow == false) {
// this.huashow=true
this.TabItemTap()
throttle(this.uploadFile(this.voicePath), 1000)
}
this.num = 0 this.num = 0
}, 500)
} else {
if (!this.risshow) {
uni.showModal({
title: "录音时长不超过3s"
})
}
}
} }
@ -799,36 +735,7 @@
}, },
toBase64() {
pathToBase64(this.voicePath)
.then(base64 => {
const arrayBuffer = new Uint8Array(base64)
const base1 = uni.arrayBufferToBase64(arrayBuffer.split(0, 1280))
let params = {
common: {
app_id: '2eda6c2e',
},
business: {
language: "zh_cn",
domain: "iat",
accent: "mandarin",
vad_eos: 5000,
dwa: "wpgs",
},
data: {
status: 2,
format: "audio/L16;rate=16000",
encoding: "raw",
audio: base1
},
};
this.audioTxt = JSON.stringify(params)
})
.catch(error => {
console.error(error)
})
},
// //
deletespeech() { deletespeech() {
@ -873,9 +780,31 @@
}, },
// //
palyaudio(item) { palyaudio1(item, i) {
this.palystatus = !this.palystatus this.palystatus = !this.palystatus
console.log(this.audio_file, '111')
if (!this.palystatus) {
this.ScanAudio(this.audio_file, this.currentIndex, 0)
} else {
this.ScanAudio(this.audio_file, this.currentIndex, 0)
// this.txtspeech(item.content, i)
}
// innerAudioContext.onError((res) => {
// console.log(res.errMsg);
// console.log(res.errCode);
// this.palystatus = true
// });
innerAudioContext.onEnded((res) => {
this.palystatus = true
});
},
//
palyaudio(item, i) {
this.palystatus = !this.palystatus
if (!this.palystatus) { if (!this.palystatus) {
innerAudioContext.src = item.audio_file; innerAudioContext.src = item.audio_file;
innerAudioContext.play() innerAudioContext.play()
@ -1051,6 +980,18 @@
let that = this; let that = this;
let moveX = this.touchMoveX - e.touches[0].pageX; let moveX = this.touchMoveX - e.touches[0].pageX;
let moveY = this.touchMoveY - e.touches[0].pageY; let moveY = this.touchMoveY - e.touches[0].pageY;
// console.log(-115 > moveX && -240 < moveX,moveY)
let platform = uni.getSystemInfoSync().platform;
if (platform === 'ios') {
if (-115 > moveX && -240 < moveX && moveY < -620 && moveY > -730) {
this.risshow = true
this.deletespeech()
} else {
this.risshow = false
}
} else {
if (-115 > moveX && -240 < moveX && moveY < -359 && moveY > -480) { if (-115 > moveX && -240 < moveX && moveY < -359 && moveY > -480) {
@ -1060,240 +1001,7 @@
} else { } else {
this.risshow = false this.risshow = false
} }
},
audiosckt() {
this.socketaudio = uni.connectSocket({
//url: encodeURI(encodeURI(myUrl).replace(/\+/g, '%2B')),
url: this.audioUrl,
method: 'GET',
token: '',
success: res => {
console.log(res, "ws成功连接...")
} }
})
// ,
this.socketaudio.onOpen((res) => {
console.log("WebSocket连接正常打开中...");
//
let params = {
common: {
app_id: '2eda6c2e',
},
business: {
language: "zh_cn",
domain: "iat",
accent: "mandarin",
vad_eos: 5000,
dwa: "wpgs",
},
data: {
status: 0,
format: "audio/L16;rate=16000",
encoding: "raw",
},
};
this.socketaudio.send({
data: JSON.stringify(params),
async success(res) {
console.log("消息发送成功", '1');
that.audioTxt = ''
},
});
//
this.handlerInterval = setInterval(() => {
//
console.log(this.audioTxt)
let that = this
this.socketaudio.send({
data: JSON.stringify({
data: {
status: 1,
format: 'audio/L16;rate=16000',
encoding: 'raw',
audio: this.audioTxt
}
}),
async success(res) {
console.log("消息发送成功", that.audioTxt, '2');
that.audioTxt = ''
},
});
if (this.audioTxt.length === 0) {
this.socketaudio.send({
data: JSON.stringify({
data: {
status: 2,
format: 'audio/L16;rate=16000',
encoding: 'raw',
audio: ''
}
}),
async success(res) {
console.log("消息发送成功", '3');
clearInterval(that.handlerInterval);
return false;
},
});
};
}, 40);
//
// this.socketaudio.send({
// data: JSON.stringify(params),
// async success(res) {
// console.log("", res);
// },
// });
//
})
// socket
// this.socketaudio.onClose(() => {
// console.log("")
// })
this.socketaudio.onMessage((res) => {
console.log("收到服务器内容:" + res.data);
});
},
send1() {
this.showStop = true;
//
let data = {
"id": new Date().getTime(),
"content": this.content,
"type": 1,
"pic": this.avatar
}
this.TEXT = this.content,
this.talkList.push(data);
this.talkList.push({
"id": new Date().getTime(),
"content": '',
"type": 2,
"pic": this.avatarType
});
this.n_content = '';
this.c_content = '';
this.socketing = true;
// return ;
this.$nextTick(() => {
//
this.content = '';
})
this.sendToSpark1();
},
async sendToSpark1() {
this.tempRes = "";
let realThis = this;
this.socketTask = uni.connectSocket({
//url: encodeURI(encodeURI(myUrl).replace(/\+/g, '%2B')),
url: `wss://chat.lihaink.cn/chat?type=${this.wssType}&timestamp=${Date.now()}`,
method: 'GET',
token: '',
success: res => {
console.log(res, "ws成功连接...")
realThis.wsLiveFlag = true;
}
})
realThis.socketTask.onError((res) => {
console.log("连接发生错误请检查appid是否填写", res)
})
realThis.socketTask.onOpen((res) => {
this.historyTextList.push({
"role": "user",
"content": this.TEXT
})
// ..........................................
console.log('连接成功...')
if (this.historyTextList.length > 9) this.params = JSON.parse(JSON.stringify(this
.historyTextList
.splice(-9)));
else this.params = JSON.parse(JSON.stringify(this.historyTextList));
this.isSurpass();
realThis.socketTask.send({ // uni
data: JSON.stringify(this.params),
success() {
console.log('第一帧发送成功');
}
});
});
//
realThis.socketTask.onMessage((res) => {
// console.log('API', res.data);
let obj = JSON.parse(res.data)
// console.log(""+obj.payload);
if (!realThis.wsLiveFlag) return;
let dataArray = obj.payload.choices.text;
for (let i = 0; i < dataArray.length; i++) {
this.talkList[this.talkList.length - 1].content += dataArray[i].content;
this.n_content = this.talkList[this.talkList.length - 1].content;
realThis.tempRes = realThis.tempRes + dataArray[i].content
}
let temp = JSON.parse(res.data)
// console.log("0726",temp.header.code)
if (temp.header.code !== 0) {
this.socketing = false;
console.log(`${temp.header.code}:${temp.message}`);
realThis.socketTask.close({
success(res) {
console.log('关闭成功', res)
realThis.wsLiveFlag = false;
},
fail(err) {
console.log('关闭失败', err)
}
})
}
if (temp.header.code === 0) {
if (res.data && temp.header.status === 2) {
this.socketing = false;
this.historyTextList.push({
"role": "assistant",
"content": this.tempRes
})
setTimeout(() => {
let that = this
realThis.socketTask.close({
success(res) {
console.log('关闭成功', res)
that.nums = that.talkList.length - 1
that.txtspeech(that.n_content, that.talkList.length -
1)
realThis.wsLiveFlag = false;
},
fail(err) {
// console.log('', err)
}
})
}, 1000)
}
}
})
}, },
// //
@ -1311,7 +1019,8 @@
"id": new Date().getTime(), "id": new Date().getTime(),
"content": this.content, "content": this.content,
"type": 1, "type": 1,
"pic": this.avatar // "pic": this.avatar
"pic": this.avatarType
} }
// console.log(data); // console.log(data);
this.TEXT = this.content; this.TEXT = this.content;
@ -1427,15 +1136,15 @@
"role": "assistant", "role": "assistant",
"content": this.tempRes "content": this.tempRes
}) })
this.nums = this.talkList.length - 1
this.txtspeech(this.n_content, this.talkList.length -
1)
setTimeout(() => { setTimeout(() => {
let that = this let that = this
realThis.socketTask.close({ realThis.socketTask.close({
success(res) { success(res) {
console.log('关闭成功', res) console.log('关闭成功', res)
that.nums = that.talkList.length - 1
that.txtspeech(that.n_content, that.talkList.length -
1)
realThis.wsLiveFlag = false; realThis.wsLiveFlag = false;
@ -1513,7 +1222,7 @@
page { page {
// background-color: #f5f5f5; // background-color: #f5f5f5;
height: 100vh; height: 100vh;
background: url('@/static/icon/bg1.png') no-repeat; // background: url('@/static/icon/bg1.png') no-repeat;
background-size: 100% 100%; background-size: 100% 100%;
background-attachment: fixed; background-attachment: fixed;
background-repeat: no-repeat; background-repeat: no-repeat;
@ -1630,7 +1339,7 @@
width: 100%; width: 100%;
padding-top: var(--status-bar-height); padding-top: var(--status-bar-height);
padding-bottom: 30rpx; padding-bottom: 30rpx;
background: url('@/static/icon/bg1.png'); // background: url('@/static/icon/bg1.png');
background-size: cover; background-size: cover;
text-align: center; text-align: center;
background-color: transparent; background-color: transparent;