HarmonyOS 鸿蒙Next播放音频
HarmonyOS 鸿蒙Next播放音频
使用AvPlayer实现项目内音频文件的播放、暂停、停止等功能
Row() {
ButtonSelectView({
name: ‘加载资源’, onclick: () => {
AvPlayerUtil.getInstance().loadResource(mContext, ‘sound_high_man.mp3’, (state) => {
this.message = ‘当前播放器状态’ + state
})
}
})
ButtonSelectView({
name: ‘播放’, onclick: () => {
AvPlayerUtil.getInstance().play()
}
})
ButtonSelectView({
name: ‘暂停’, onclick: () => {
AvPlayerUtil.getInstance().pause()
}
})
ButtonSelectView({
name: ‘释放资源’, onclick: () => {
AvPlayerUtil.getInstance().release()
}
})
}
.width(‘100%’)
.justifyContent(FlexAlign.SpaceEvenly)
.margin(20)
/
* 闲置状态
*/
let idle: string = ‘idle’
/
* 资源初始化
*/
let initialized: string = ‘initialized’
/
* 已准备
*/
let prepared: string = ‘prepared’
/
* 正在播放
*/
let playing: string = ‘playing’
/
* 暂停状态
*/
let paused: string = ‘paused’
/
* 已结束
*/
let completed: string = ‘completed’
/
* 已停止
*/
let stopped: string = ‘stopped’
/
* 已销毁
*/
let released: string = ‘released’
/
* 错误异常
*/
let error: string = 'error’
export class AvPlayerUtil {
private static instance: AvPlayerUtil
private avPlayer?: media.AVPlayer
private onStateChange?: (state: string) => void
private constructor() {
}
static getInstance(): AvPlayerUtil {
if (AvPlayerUtil.instance == null) {
AvPlayerUtil.instance = new AvPlayerUtil()
}
return AvPlayerUtil.instance
}
/
* 加载资源文件
* @param resName 项目中rawfile文件下的音视频资源文件的名字
*/
async loadResource(mContext: common.UIAbilityContext, resName: string, onStateChange?: (state: string) => void) {
this.onStateChange = onStateChange
//如果播放器存在,并且运行中,先将原来的注销掉再创建新的并且加载资源
if (this.avPlayer != null && this.avPlayer.state != ‘released’) {
this.avPlayer.release()
}
//创建实例
this.avPlayer = await media.createAVPlayer()
//监听状态
this.setAVPlayerCallback(this.avPlayer)
let fileDescriptor = await mContext.resourceManager.getRawFd(resName)
//加载资源
this.avPlayer.fdSrc = { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length }
}
/
* 播放音视频
*/
play() {
return this.avPlayer?.play()
}
/
* 暂停播放
*/
pause() {
return this.avPlayer?.pause()
}
/
* 停止播放
*/
stop() {
return this.avPlayer?.stop()
}
/
* 释放资源
*/
release() {
return this.avPlayer?.release()
}
/**
* 监听运行状态
*/
private setAVPlayerCallback(avPlayer: media.AVPlayer) {
avPlayer.on(‘error’, (err: BusinessError) => {
avPlayer.reset(); // 调用reset重置资源,触发idle状态
})
avPlayer.on(‘stateChange’, async (state: string, reason: media.StateChangeReason) => {
if (this.onStateChange != null) {
this.onStateChange(state)
}
switch (state) {
case idle: // 闲置状态
avPlayer.release(); // 调用release接口销毁实例对象
break;
case initialized: //资源初始化
avPlayer.prepare(); //调用准备方法
break;
case stopped: //播放停止
avPlayer.reset(); //重置资源
break;
case error:
avPlayer.reset(); //重置资源
break
}
})
}
}
1 回复
在HarmonyOS(鸿蒙)系统中播放音频,你需要确保你的应用已经正确获得了音频播放的权限,并且使用了合适的API来管理音频播放。通常,你可以通过MediaPlayer或SoundPool等类来实现音频的播放。确保你的音频文件路径正确,并且格式被系统支持。
此外,检查你的应用是否在合适的生命周期阶段(如Activity的onResume中)启动音频播放,并正确处理异常和错误状态。
如果问题依旧没法解决请加我微信,我的微信是itying888。