【Harmony Next】使用 AVPlayer 播放音频

在鸿蒙Next系统中,AVPlayer为开发者提供了强大的音频播放功能。以下将详细介绍如何使用AVPlayer来实现音频播放。

官方文档:使用AVPlayer播放音频(ArkTS)

播放状态变化示意图

基本使用步骤

  1. 创建AVPlayer实例:通过media.createAVPlayer()方法创建AVPlayer实例,用于控制音频的播放。示例代码如下:
async createAVPlayerInstance() {
 const avPlayer = await media.createAVPlayer(); // 异步
 return avPlayer;
}
  1. 设置播放源:指定本地 rawFile 路径,如 test.mp3
 async setSourcePath(path: string) {
 setTimeout(async () => {
 if (!this.checkNull()) {
 try {
 let context = getContext(this) as common.UIAbilityContext;
 let fileDescriptor = await context.resourceManager.getRawFd(path);
 let fileFd: number = JSON.parse(JSON.stringify(fileDescriptor))['fd']
 let fileOffset: number = JSON.parse(JSON.stringify(fileDescriptor))['offset']
 this.avFileDescriptor = { fd: fileFd, offset: fileOffset, length: -1 };
 this.avPlayer!.fdSrc = this.avFileDescriptor;
 } catch (err) {
 console.info('Set Url failed : ' + JSON.stringify(err))
 }
 }
 }, 500)
}
  1. 监听状态变化:监听stateChange事件来了解播放器的状态,从而做出相应操作。示例代码如下:

/**
 * avplayer回调
 */
private setAVPlayerCallback() {
 if (this.checkNull()) {
 return
 }
 // seek操作结果回调
 this.avPlayer!.on('seekDone', (seekDoneTime) => {
 console.info(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`);
 })
 // 音量变化回调
 this.avPlayer!.on('volumeChange', (volume) => {
 console.info(`volumeChange called, and new volume is :${volume}`);
 })
 // 音频总时长
 this.avPlayer!.on('durationUpdate', (duration) => {
 console.info(`durationUpdate :${duration}`);
 })
 // 当前播放进度
 this.avPlayer!.on('timeUpdate', (time) => {
 let now = Math.floor(time/1000)
 if (this.process != now) {
 console.info(`timeUpdate :${now}`);
 }
 this.process = now
 })
 // error回调监听函数,当avPlayer在操作过程中出现错误时调用reset接口触发重置流程
 this.avPlayer!.on('error', (err) => {
 console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`);
 this.avPlayer!.reset(); // 调用reset重置资源,触发idle状态
 })
 // 状态机变化回调函数
 this.avPlayer!.on('stateChange', async (state, reason) => {
 switch (state) {
 case 'idle': // 成功调用reset接口后触发该状态机上报
 console.info('AVPlayer state idle called.');
 this.avPlayer!.release(); // 调用release接口销毁实例对象
 break;
 case 'initialized': // avplayer 设置播放源后触发该状态上报
 console.info('AVPlayer state initialized called.');
 this.avPlayer!.prepare().then(() => {
 console.info('AVPlayer prepare succeeded.');
 }, () => {
 console.error(`Invoke prepare failed, code is`);
 });
 break;
 case 'prepared': // prepare调用成功后上报该状态机
 console.info('AVPlayer state prepared called.');
 this.avPlayer!.loop = this.loop
 this.avPlayer!.setVolume(this.volume)
 if (this.autoPlay) {
 this.avPlayer!.play(); // 调用播放接口开始播放
 }
 break;
 case 'playing': // play成功调用后触发该状态机上报
 console.info('AVPlayer state playing called.');
 break;
 case 'paused': // pause成功调用后触发该状态机上报
 console.info('AVPlayer state paused called.');
 break;
 case 'completed': // 播放结束后触发该状态机上报
 console.info('AVPlayer state completed called.');
 if (this.loop == true) {
 this.avPlayer!.seek(0)
 this.avPlayer!.play()
 }
 break;
 case 'stopped': // stop接口成功调用后触发该状态机上报
 console.info('AVPlayer state stopped called.');
 break;
 case 'released':
 console.info('AVPlayer state released called.');
 break;
 default:
 console.info('AVPlayer state unknown called.');
 break;
 }
 })
}
  1. 控制音频播放:可以调用play()pause()stop()seek()等方法对音频进行播放、暂停、停止、跳转等操作。示例代码如下:

play() {
 if (this.checkNull()) {
 this.autoPlay = true
 return
 }
 this.avPlayer!.play().then(() => {
 console.info('Play success')
 }).catch((err: BusinessError) => {
 console.info('Play failed : ' + JSON.stringify(err))
 })
}
pause() {
 if (this.checkNull()) {
 this.autoPlay = false
 return
 }
 this.avPlayer!.pause().then(() => {
 console.info('Pause success')
 }).catch((err: BusinessError) => {
 console.info('Pause failed : ' + JSON.stringify(err))
 })
}
release() {
 if (this.checkNull()) {
 this.autoPlay = false
 return
 }
 this.avPlayer!.release().then(() => {
 console.info('Release success')
 setTimeout(() => {
 }, 500)
 }).catch((err: BusinessError) => {
 console.info('Release failed : ' + JSON.stringify(err))
 })
}
setVolume(volume: number) {
 console.info(`setVolume ${volume}`)
 this.volume = volume
 if (this.checkNull()) {
 return
 }
 this.avPlayer!.setVolume(volume)
}
setLoop() {
 console.info('setLoop')
 this.loop = true
 if (this.checkNull()) {
 return
 }
 this.avPlayer!.loop = true
}

设置音量和循环播放时需要在状态 prepared 后调用,否则会报错

Invoke avPlayer failed, code is 5400102, message is Operate Not Permit: current state is not prepared/playing/paused/completed, unsupport loop operation
  1. 释放资源:当音频播放完成或者不再需要播放时,调用release()方法释放资源,避免内存泄漏。示例代码如下:
async function releasePlayer(avPlayer) {
 await avPlayer.release();
}

注意事项

  • 权限申请:如果要访问在线媒体资源,需要在配置文件中申请ohos.permission.INTERNET权限。
  • 资源格式:确保音频文件格式与鸿蒙系统支持的格式兼容,以避免无法播放的情况。
  • 异常处理:在播放过程中可能会遇到网络中断、文件损坏等异常情况,需要添加异常处理逻辑,如监听error事件来进行相应处理。

希望通过以上介绍,能帮助开发者在鸿蒙Next应用开发中熟练使用AVPlayer实现音频播放功能,为用户带来更好的音频体验。

本文由博客一文多发平台 OpenWrite 发布!

作者:Brian512原文地址:https://www.cnblogs.com/brian512/p/18757655

%s 个评论

要回复文章请先登录注册