0
点赞
收藏
分享

微信扫一扫

使用uniapp的websocket发送语音

<template>
<view>
<button @tap="startRecord">开始录音</button>
<button @tap="endRecord">停止录音</button>
<button @tap="playVoice">播放录音</button>
<view class="" style="text-align: center;padding-top: 100rpx;">
{{txtmgs}}
</view>
<button @click="playVoice2">播放录音2</button>
</view>
</template>

<script>
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
let self
export default {
data() {
return {
text: 'uni-app',
voicePath: '',
txtmgs:'',
ssc:'',
}
},
onLoad() {
self = this;
this.connectScoketInit()
recorderManager.onStop(function(res) {
console.log('recorder stop' + JSON.stringify(res));
self.txtmgs=JSON.stringify(res)
self.voicePath = res.tempFilePath;
self.audio2dataURL(res.tempFilePath)
});
},
beforeDestroy() {
this.closeSocket()
},
methods: {
startRecord() {
console.log('开始录音');
self.txtmgs='开始录音'
recorderManager.start();
},
endRecord() {
console.log('录音结束');
self.txtmgs='录音结束'
recorderManager.stop();
},
playVoice() {
console.log('播放录音');
self.txtmgs='播放录音'

if (this.voicePath) {
innerAudioContext.src = this.voicePath;
innerAudioContext.play();
}
},
playVoice2(){
console.log('播放录音2');
self.txtmgs='播放录音2'

innerAudioContext.src = self.ssc;
innerAudioContext.play();

},
audio2dataURL (path) {
console.log('----------audio2dataURL-----------')
plus.io.resolveLocalFileSystemURL(path, function(entry){
entry.file(function(file){
var reader = new plus.io.FileReader();
reader.readAsDataURL(file);
reader.onloadend = function (e) {
console.log('----------语音转换结果------------')
// console.log(e.target.result);
// 这里websoket发送
self.sendMsg(e.target.result)
console.log('----------发送语音完成------------')
};
},function(e){
mui.toast("读写出现异常: " + e.message );
})
})
},
connectScoketInit() {
this.socketTask = uni.connectSocket({
url: "ws://192.168.31.99:8080/Test",
data() {
return {
x: '11',
y: '22'
};
},
success(data) {
console.log("websocket链接成功")
}
})

this.socketTask.onOpen((res) => {
console.log("websocket链接正常打开在……");

this.is_open_socket = true;
this.socketTask.send({
data: "uni-app-01发送一条消息",
async successs() {
console.log("消息发送成功");
}
})
// this.socketTask.onMessage(function(res) {
// console.log("收到服务器内容:" + res.data);
// let imgurl="http://192.168.31.40:8080/down1/"+res.data
// console.log(imgurl)
// self.ssc=imgurl
// // _this.title = res.data
// })
})
this.socketTask.onClose(function() {
console.log("已经关闭了")
})
},
closeSocket() {
this.socketTask.close({
success(res) {
this.is_open_socket = false
console.log("关闭成功", res)
},
fail(err) {
console.log("关闭失败", err)
}
})
},
sendMsg(msg) {
if (this.is_open_socket) {
this.socketTask.send({
data:msg,
async success() {
console.log("消息发送成功")
}
})
}
},
},



}
</script>

<style>

</style>

举报

相关推荐

0 条评论