本篇文章主要记录的是,用taro框架开发跨端的录音功能遇到的问题
第一部分:录音功能
h5端
h5端由于每个浏览器实现方式都不一样,存在着较大的差异,个人去实现成本太高,所以直接引用社区的一个成熟的包,recorder。这个包已经实现了对大部分浏览器的支持,也支持微信公众号。支持安卓内嵌h5;ios端内嵌的h5,需要ios原生提供api支持。
// 开始
start = () => {
this.recorderManager = Recorder({
type: 'mp3',
sampleRate: 16000,
bitRate: 16
})
//需要先打开授权才能录音
this.recorderManager.open(() => {
this.recorderManager.start()
})
}
stop = () => {
this.recorderManager.stop(
(blob, duration) => {
this.recorderManager.close()
// 释放录音资源,当然可以不释放,后面可以连续调用start;但不释放时系统或浏览器会一直提示在录音,最佳操作是录完就close掉
this.recorderManager = null
// 简单利用URL生成播放地址,注意不用了时需要revokeObjectURL,否则霸占内存
const audioSrc = (window.URL || webkitURL).createObjectURL(blob)
},
err => {
console.log(err)
}
)
}
微信
小程序
initRecorderManager = () => {
this.recorderManager = Taro.getRecorderManager()
const startFunc = () => {}
const stopFunc = res => {
const audioSrc = res.tempFilePath || res.apFilePath
}
const errFunc = err => {}
this.recorderManager.onStart(startFunc)
this.recorderManager.onStop(stopFunc)
this.recorderManager.onError(errFunc)
}
start = () => {
//全局只有一个管理器,每次都要重新初始化,不然使用多个的时候会互相影响
this.initRecorderManager()
}
stop = () => {
this.recorderManager.stop()
}
公众号
这部分可以直接使用recorder包,已经支持了公众号录音的功能
钉钉端
小程序
initRecorderManager = () => {
this.recorderManager = Taro.getRecorderManager()
const startFunc = () => {}
const stopFunc = res => {
const audioSrc = res.tempFilePath || res.apFilePath
}
const errFunc = err => {}
//注意这个写法跟微信端不一样
this.recorderManager.onstart = startFunc
this.recorderManager.onstop = stopFunc
this.recorderManager.onerror = errFunc
}
start = () => {
//全局只有一个管理器,每次都要重新初始化,不然使用多个的时候会互相影响
this.initRecorderManager()
}
stop = () => {
this.recorderManager.stop()
}
微应用
注意
- onRecordEnd方法必须在start之前调用,写在其他地方调用会不生效
- 录音的文件是放在钉钉服务器,只要企业不解散,就可以永久存储
- 调用的api需要授权才能使用
start = () => {
//监听超过60s自动停止,而且必须写在start之前才有效
window.dd.device.audio.onRecordEnd({
onSuccess: res => {
const mediaId = res.mediaId
},
onFail: err => {
console.log(err)
}
})
//此处如果用其他跨端软件,可以调用相对应的方法
Taro.startRecord()
}
stop = () => {
Taro.stopRecord({
success: (res: any) => {
const mediaId = res.mediaId
}
})
}
支付宝端
支付宝webview内嵌的h5不支持录音功能,支付宝小程序官方文档也没有提供录音api,不过写法可以参考上面的微信写法,暂时可用。
第二部分:播放功能
h5端
h5端如果用的不是taro开发,还是可以参考recorder的实现方式。如果用taro开发:
start = () => {
this.audioManager = Taro.createInnerAudioContext()
this.audioManager.src = audioSrc
this.audioManager.play()
}
stop = () => {
this.audioManager.stop()
}
钉钉端
小程序
注意:
- src赋值和play方法同时调用,在ios上会出现播放问题,所以设置src的同时不要调用play方法
- ios会出现无法播放的问题,如果是mp3的文件,必须先下载,才能播放
start = (url) => {
this.audioManager = Taro.createInnerAudioContext()
Taro.downloadFile({
url,
success: res => {
this.audioManager.src = res.filePath || res.apFilePath || res.tempFilePath
}
})
}
stop = () => {
this.audioManager.stop()
}
微应用
注意
- 安卓端,必须先下载才能播放
start = (id) => {
window.dd.device.audio.download({
mediaId: id,
onSuccess: res => {
window.dd.device.audio.play({
localAudioId: res.localAudioId,
})
}
})
}
stop = (id) => {
window.dd.device.audio.stop({
localAudioId: id
})
}