})
//停止录音回调
recorderManager.onStop((res) => {
console.log(‘录音停止’, res)
console.log(‘录音保存路径’ + res.tempFilePath)
})
audioCtx.onPlay(()=>{
console.log(‘开始播放’)
})
Page({
//开始录音
record: function () {
recorderManager.start()
},
//暂停
pause: function () {
recorderManager.pause()
},
//停止
stop: function () {
recorderManager.stop()
},
})
三 小程序播放音频相关的API——InnerAudioContext
3.1 创建audio对象
const audioCtx = wx.createInnerAudioContext()
3.2 方法及说明
| 方法 | 参数 | 说明 |
| :-: | :-: | :-: |
| play | - | 播放 |
| onPlay | callback | 监听音频播放事件 |
| pause | - | 暂停 |
| onPause | callback | 监听音频暂停事件 |
| seek | position | 跳转到指定位置 |
| onSeeking | callback | 监听音频进行跳转操作的事件 |
| onSeeked | callback | 监听音频完成跳转操作的事件 |
| stop | - | 停止 |
| onStop | callback | 监听音频停止事件 |
3.3 示例
var recorderManager = wx.getRecorderManager()
var tempFilePath = null
const audioCtx = wx.createInnerAudioContext()
//开始录音回调
recorderManager.onStart(() => {
console.log(‘开始录音’)
})
//暂停录音回调
recorderManager.onPause(() => {
console.log(‘录音暂停’)
})
//停止录音回调
recorderManager.onStop((res) => {
console.log(‘录音停止’, res)
console.log(‘录音保存路径’ + res.tempFilePath)
tempFilePath=res.tempFilePath
})
audioCtx.onPlay(()=>{
console.log(‘开始播放’)
})
Page({
//开始录音
record: function () {
recorderManager.start()
},
//暂停
pause: function () {
recorderManager.pause()
},
//停止
stop: function () {
recorderManager.stop()
},
//回放
playback:function(){
audioCtx.src=tempFilePath
audioCtx.play()
}
})
4.1 说明
将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中 content-type
为 multipart/form-data
4.2 属性及说明
| 属性 | 参数 | 说明 |
| :-: | :-: | :-: |
| url | string | 开发者服务器地址 |
| filePath | string | 要上传文件资源的路径 (本地路径) |
| name | string | 文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容 |
| header | Object | HTTP 请求 Header,Header 中不能设置 Referer |
| formData | Object | HTTP 请求中其他额外的 form data |
| timeout | number | 超时时间,单位为毫秒 |
| success | function | 接口调用成功的回调函数 |
| fail | function | 接口调用失败的回调函数 |
| complete | function | 接口调用结束的回调函数(调用成功、失败都会执行) |
4.3 示例
wx.chooseImage({
success (res) {
const tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: ‘https://example.weixin.qq.com/upload’, //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: ‘file’,
formData: {
‘user’: ‘test’
},
success (res){
const data = res.data
//do something
}
})
}
})
5.1 说明
-
下载文件资源到本地。客户端直接发起一个 HTTPS GET 请求,返回文件的本地临时路径 (本地路径),单次下载允许的最大文件为 200MB
-
请在服务端响应的 header 中指定合理的
Content-Type
字段,以保证客户端正确处理文件类型
5.2 属性及说明(同上)
5.3 示例
wx.downloadFile({
url: ‘https://example.com/audio/123’, //仅为示例,并非真实的资源
success (res) {
// 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
if (res.statusCode === 200) {
wx.playVoice({
filePath: res.tempFilePath
})
}
}
})