以下js 实现了微信小程序播放 停止 暂停等 音频播放。
import { formatTime } from "./index"; /** * 通用声音播放器 * @param url 音频路径 * @param onComplete 播放完成回调 */ export function play(url, onComplete) { //this. if (_isVoice(url)) { if (_isLocalFile(url)) { //播放本地文件 _playVoice(url, onComplete); } else { //下载到本地并播放 _download(url).then( localPath => {this._playVoice(localPath, onComplete);},//下载成功 fail => {onComplete()}//下载失败 ); } } else { //播放在线音频 _playAudio(url, onComplete); } } /** * 通用声音停止 */ export function stop() { console.log("停止") _stopAudio(); _stopVoice(); } /** * 播放在线声音 * @param url * @param onComplete */ function _playAudio(url, onComplete = () => {}) { wx.onBackgroundAudioStop(() => {}); wx.stopBackgroundAudio({ complete(){ wx.playBackgroundAudio({ dataUrl: url }); wx.onBackgroundAudioStop(() => { onComplete(); wx.onBackgroundAudioStop(() => {});//防止单独掉微信playBackgroundAudio接口时再次回调 }); } }); } /** * 停止播放在线声音 */ function _stopAudio() { //wx.onBackgroundAudioStop(() => {}); //wx.stopBackgroundAudio(); var BackgroundAudioManager = wx.getBackgroundAudioManager(); BackgroundAudioManager.stop(); } /** * 播放本地语音 * @param recordUrl * @param onComplete */ function _playVoice(recordUrl, onComplete = () => {}) { wx.stopVoice({ complete(){ setTimeout(function () { wx.playVoice({ filePath: recordUrl, complete(){ onComplete(); } }); }, 500);//设置延迟以防两个音频同时放时回调冲突 } }) } /** * 停止播放本地语音 */ function _stopVoice() { wx.stopVoice(); } function _isVoice(url) { return url.endsWith(".silk"); } function _isLocalFile(url) { return url.startsWith("wxfile:") } function _download(url) { return new Promise((resolve, reject) => { wx.downloadFile({ url: url, success(res) { resolve(res.tempFilePath); }, fail(res){ reject(res); } }) }); } export default { play: play, stop: stop }