微信小程序-语音输入(录音并播放)

时间:2024-04-03 11:00:00
// expertConsultations/addQuestion/index/index.js const httpUtils = require("../../../utils/httpUtils") const stringUtils = require("../../../utils/stringUtils") const app = getApp() //定义一个全局变量,调用微信官方定义语音管理对象 const recorderManager = wx.getRecorderManager(); Page({ /** * 页面的初始数据 */ data: { phone: '', questionTypeIndex: '', questionTypeOptions: [], title: "", info: "", biaoQian: "", imgFiles: [], zid: '', }, /** * 生命周期函数--监听页面加载 */ onLoad(options) { this.setData({ zid: options.id }) }, onInput() {}, cancelTap() { wx.navigateBack() }, //语音开始 audiostart: function () { wx.showToast({ title: '正在录音...', icon: 'loading', duration: 10000 }); recorderManager.start({ format: 'mp3' }); }, //语音结束 audioend: function () { //弹窗消失 wx.hideToast({ title: '正在录音...', icon: 'loading' }); var path = ""; var that = this; recorderManager.stop(); recorderManager.onStop(function (res) { path = res.tempFilePath; console.log("结束", res) console.log(res.tempFilePath) if (res.duration < 1000) { wx.showModal({ title: '录音时长太短,请重新录音', content: '', }) } else { if (res.tempFilePath != "") { console.log(that.data.imgFiles); that.setData({ imgFiles: that.data.imgFiles.concat([{ url: res.tempFilePath, tempFilePath: res.tempFilePath, fileType: 'mp3', duration: parseInt(res.duration / 1000) }]) }); console.log(2, that.data.imgFiles); //将语音文件保存至后台 // that.saveVoiceInfo(res.tempFilePath); } else { } } }); }, playVoice() { // 获取innerAudioContext实例 const innerAudioContext = wx.createInnerAudioContext() // 是否自动播放 innerAudioContext.autoplay = true // 设置音频文件的路径 innerAudioContext.src = this.data.tempFilePath; // 播放音频文件 innerAudioContext.onPlay(() => { console.log('开始播放') }); // 监听音频播放错误事件 innerAudioContext.onError((res) => { console.log(res.errMsg) }) }, //保存至后台 saveVoiceInfo: function (path) { var that = this; }, })