💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
> 本文主要介绍一下音频组建,官方推荐使用API方式进行创建,而不建议[使用组建方式](https://uniapp.dcloud.io/component/audio),因为灵活性差,所以使用API方式进行替换 * [播放音频 (使用 uni.createInnerAudioContext)](https://www.kancloud.cn/wangking/uniapp/1968386#__unicreateInnerAudioContext_3) * [播放背景音频 (使用 uni.getBackgroundAudioManager)](https://www.kancloud.cn/wangking/uniapp/1968386#__unigetBackgroundAudioManager_39) * [录音功能 (使用 uni.getRecorderManager)](https://www.kancloud.cn/wangking/uniapp/1968386#__unigetRecorderManager_60) ## 播放音频 (使用 uni.createInnerAudioContext) > 高阶示例代码,可参考hello-uni里的demo > 官方文档:[https://uniapp.dcloud.io/api/media/audio-context](https://uniapp.dcloud.io/api/media/audio-context) ~~~ <template> <view class="page"> <button type="default" @tap="play">播放或继续音乐</button> <button type="default" @tap="pause">暂停音乐</button> <button type="default" @tap="stop">停止音乐</button> </view> </template> <script> // 地址可在 http://www.gequdaquan.net/gqss/ 获取 const audioUrl = 'http://m7.music.126.net/20201009174647/76faa967ae92e6b239a950157923c6c1/ymusic/8e8b/9cae/42b8/f4b218f89f27791d1defdfaa4a4862e7.mp3' const innerAudioContext = uni.createInnerAudioContext(); export default { onLoad() { innerAudioContext.src = audioUrl }, methods: { play() { console.log(innerAudioContext.src) innerAudioContext.play(); }, pause() { innerAudioContext.pause(); }, stop() { innerAudioContext.stop(); } } } </script> ~~~ ## 播放背景音频 (使用 uni.getBackgroundAudioManager) > 背景音频就是 App在后台时,仍然在播放音乐 ~~~ <template> <view> 背景音乐播放中 </view> </template> <script> export default { onLoad() { const bgAudioMannager = uni.getBackgroundAudioManager(); bgAudioMannager.title = '致爱丽丝'; bgAudioMannager.singer = 'wangkun'; bgAudioMannager.coverImgUrl = 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/doc/uniapp4@2x.png'; bgAudioMannager.src = 'http://m7.music.126.net/20201009174647/76faa967ae92e6b239a950157923c6c1/ymusic/8e8b/9cae/42b8/f4b218f89f27791d1defdfaa4a4862e7.mp3'; } } </script> ~~~ ## 录音功能 (使用 uni.getRecorderManager) > 官方文档:[https://uniapp.dcloud.io/api/media/record-manager](https://uniapp.dcloud.io/api/media/record-manager) ~~~ <template> <view> <button @tap="startRecord">开始录音</button> <button @tap="endRecord">停止录音</button> <button @tap="playVoice">播放录音</button> </view> </template> <script> const recorderManager = uni.getRecorderManager(); const innerAudioContext = uni.createInnerAudioContext(); innerAudioContext.autoplay = true; var _this; export default { data(){ return { voicePath : '' } }, onLoad() { _this = this; recorderManager.onStop(function(res) { console.log(res) _this.voicePath = res.tempFilePath // 使用uni.uploadFile上传到服务器上,此时是mp3格式 }); }, methods: { startRecord() { console.log('开始录音'); recorderManager.start({ sampleRate: 16000 // 必须设置是后台设置的参数,不然百度语音识别不了 }); }, endRecord() { console.log('录音结束'); _this = this; recorderManager.stop(); }, playVoice() { console.log('播放录音'); if (this.voicePath) { innerAudioContext.src = this.voicePath; innerAudioContext.play(); } } } } </script> ~~~