HarmonyOS 鸿蒙Next 请问使用AVPlayer播放.wav文件 隔一次可以正常播放是什么原因

发布于 1周前 作者 sinazl 最后一次编辑是 5天前 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 请问使用AVPlayer播放.wav文件 隔一次可以正常播放是什么原因

import media from ‘@ohos.multimedia.media’;
import common from ‘@ohos.app.ability.common’;
import { BusinessError } from ‘@ohos.base’;
import fs from ‘@ohos.file.fs’;

export class AVPlayerDemo { private avPlayer: media.AVPlayer | undefined private count: number = 0; private isSeek: boolean = true; // 用于区分模式是否支持seek操作

constructor() { media.createAVPlayer((error: BusinessError, video: media.AVPlayer) => { if (video != null) { this.avPlayer = video; console.info(‘Succeeded666 in creating AVPlayer’); } else { console.error(Failed to create AVPlayer, error message:${error.message}); } }) }

// 注册avplayer回调函数 setAVPlayerCallback(avPlayer: media.AVPlayer) { // seek操作结果回调函数 avPlayer.on(‘seekDone’, (seekDoneTime: number) => { console.info(AVPlayer seek succeeded, seek time is ${seekDoneTime}); }) // error回调监听函数,当avPlayer在操作过程中出现错误时调用 reset接口触发重置流程 avPlayer.on(‘error’, (err: BusinessError) => { console.error(Invoke avPlayer failed, code is ${err.code}, message is ${err.message}); avPlayer.reset(); // 调用reset重置资源,触发idle状态 }) // 状态机变化回调函数 avPlayer.on(‘stateChange’, async (state: string, reason: media.StateChangeReason) => { switch (state) { case ‘idle’: // 成功调用reset接口后触发该状态机上报 console.info(‘AVPlayer state idle called.’); avPlayer.release(); // 调用release接口销毁实例对象 break; case ‘initialized’: // avplayer 设置播放源后触发该状态上报 console.info(‘AVPlayer state initialized called.’); avPlayer.prepare(); break; case ‘prepared’: // prepare调用成功后上报该状态机 console.info(‘AVPlayer state prepared called.’); avPlayer.play(); // 调用播放接口开始播放 break; case ‘playing’: // play成功调用后触发该状态机上报 console.info(‘AVPlayer state playing called.’); if (this.count !== 0) { if (this.isSeek) { console.info(‘AVPlayer start to seek.’); avPlayer.seek(avPlayer.duration); //seek到音频末尾 } else { // 当播放模式不支持seek操作时继续播放到结尾 console.info(‘AVPlayer wait to play end.’); } } else { // avPlayer.pause(); // 调用暂停接口暂停播放 } this.count++; break; case ‘paused’: // pause成功调用后触发该状态机上报 console.info(‘AVPlayer state paused called.’); // avPlayer.play(); // 再次播放接口开始播放 break; case ‘completed’: // 播放结束后触发该状态机上报 console.info(‘AVPlayer state completed called.’); // avPlayer.stop(); //调用播放结束接口 break; case ‘stopped’: // stop接口成功调用后触发该状态机上报 console.info(‘AVPlayer state stopped called.’); // avPlayer.reset(); // 调用reset接口初始化avplayer状态 break; case ‘released’: console.info(‘AVPlayer state released called.’); this.avPlayer = await media.createAVPlayer() this.avPlayer.prepare() break; default: console.info(‘AVPlayer state unknown called.’); break; } }) }

// 以下demo为使用资源管理接口获取打包在HAP内的媒体资源文件并通过fdSrc属性进行播放示例 async avPlayerFdSrcDemo() { // 创建状态机变化回调函数 this.setAVPlayerCallback(this.avPlayer!); // 通过UIAbilityContext的resourceManager成员的getRawFd接口获取媒体资源播放地址 // 返回类型为{fd,offset,length},fd为HAP包fd地址,offset为媒体资源偏移量,length为播放长度 let context = getContext(this) as common.UIAbilityContext; let fileDescriptor = await context.resourceManager.getRawFd(‘11582.mp3’); // let fileDescriptor = await context.resourceManager.getRawFd(‘1.wav’);

let avFileDescriptor: media.AVFileDescriptor = { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length }; this.isSeek = false; // 支持seek操作 // 为fdSrc赋值触发initialized状态机上报 this.avPlayer!.fdSrc = avFileDescriptor;

}

// 以下demo为使用fs文件系统打开沙箱地址获取媒体文件地址并通过url属性进行播放示例 // async avPlayerUrlDemo(path: string) { // // 创建avPlayer实例对象 // let avPlayer: media.AVPlayer = await media.createAVPlayer(); // // 创建状态机变化回调函数 // this.setAVPlayerCallback(avPlayer); // let fdPath = ‘fd://’; // // 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例 // // let context = getContext(this) as common.UIAbilityContext; // // let pathDir = context.filesDir; // // let path = pathDir + ‘/pCdJNp/1.wav’; // // console.log(path123456: ${path}); // // 打开相应的资源文件地址获取fd,并为url赋值触发initialized状态机上报 // let file = await fs.open(path); // fdPath = fdPath + ‘’ + file.fd; // this.isSeek = true; // 支持seek操作 // avPlayer.url = fdPath; // } // 以下demo为使用fs文件系统打开沙箱地址获取媒体文件地址并通过url属性进行播放示例 async avPlayerUrlDemo(path: string) { // 创建avPlayer实例对象 // let avPlayer: media.AVPlayer = await media.createAVPlayer(); // 创建状态机变化回调函数 this.setAVPlayerCallback(this.avPlayer!); let fdPath = ‘fd://’; // 打开相应的资源文件地址获取fd,并为url赋值触发initialized状态机上报 let file = await fs.open(path); fdPath = fdPath + ‘’ + file.fd;

let avFileDescriptor: media.AVFileDescriptor = { fd: file.fd }; this.isSeek = false; // 支持seek操作 // 为fdSrc赋值触发initialized状态机上报 this.avPlayer!.fdSrc = avFileDescriptor; }

async stop() { this.avPlayer?.stop() }

async play() { this.avPlayer?.play() }

async reset() { this.avPlayer?.reset() }

async pause() { this.avPlayer?.pause() } }

使用avPlayerUrlDemo这个方法播放,第一次正常播放,第二次没有声音,第三次正常播放

2 回复
import media from '[@ohos](/user/ohos).multimedia.media';
import common from '[@ohos](/user/ohos).app.ability.common';
import { BusinessError } from '[@ohos](/user/ohos).base';
import fs from '[@ohos](/user/ohos).file.fs';

export class AVPlayerDemo {
private avPlayer: media.AVPlayer | undefined
private count: number = 0;
private isSeek: boolean = true; // 用于区分模式是否支持seek操作

constructor() {
media.createAVPlayer((error: BusinessError, video: media.AVPlayer) => {
if (video != null) {
this.avPlayer = video;
console.info('Succeeded666 in creating AVPlayer');
} else {
console.error(`Failed to create AVPlayer, error message:${error.message}`);
}
})
}

// 注册avplayer回调函数
setAVPlayerCallback(avPlayer: media.AVPlayer, isPause?: boolean) {
// seek操作结果回调函数
avPlayer.on('seekDone', (seekDoneTime: number) => {
console.info(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`);
})
// error回调监听函数,当avPlayer在操作过程中出现错误时调用 reset接口触发重置流程
avPlayer.on('error', (err: BusinessError) => {
console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`);
avPlayer.prepare(); // 调用reset重置资源,触发idle状态
})
// 状态机变化回调函数
avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
switch (state) {
case 'idle': // 成功调用reset接口后触发该状态机上报
console.info('AVPlayer state idle called.');
avPlayer.release(); // 调用release接口销毁实例对象
break;
case 'initialized': // avplayer 设置播放源后触发该状态上报
console.info('AVPlayer state initialized called.');
avPlayer.prepare();
break;
case 'prepared': // prepare调用成功后上报该状态机
console.info('AVPlayer state prepared called.');
avPlayer.play(); // 调用播放接口开始播放
break;
case 'playing': // play成功调用后触发该状态机上报
console.info('AVPlayer state playing called.');
if (this.count !== 0) {
if (this.isSeek) {
console.info('AVPlayer start to seek.');
avPlayer.seek(avPlayer.duration); //seek到音频末尾
} else {
// 当播放模式不支持seek操作时继续播放到结尾
console.info('AVPlayer wait to play end.');
}
} else {
// avPlayer.pause(); // 调用暂停接口暂停播放
}
this.count++;
break;
case 'paused': // pause成功调用后触发该状态机上报
console.info('AVPlayer state paused called.');
console.log('isPause:', isPause + '')
if (isPause) {
avPlayer.play()
}
// avPlayer.play(); // 再次播放接口开始播放
break;
case 'completed': // 播放结束后触发该状态机上报
console.info('AVPlayer state completed called.');
// avPlayer.stop(); //调用播放结束接口
break;
case 'stopped': // stop接口成功调用后触发该状态机上报
console.info('AVPlayer state stopped called.');
// avPlayer.reset(); // 调用reset接口初始化avplayer状态
break;
case 'released':
console.info('AVPlayer state released called.');
this.avPlayer = await media.createAVPlayer()
this.avPlayer.prepare()
break;
default:
console.info('AVPlayer state unknown called.');
break;
}
})
}

下面是我用来播放的代码
import { AVPlayerDemo } from './AVPlayerDemo'
import { common } from '[@kit](/user/kit).AbilityKit'
import { media } from '[@kit](/user/kit).MediaKit'

[@Entry](/user/Entry)
[@Component](/user/Component)
struct SheetTransitionExample {
[@State](/user/State) isPause: boolean = false
avlPlayer = new AVPlayerDemo()
[@State](/user/State) isPlay: boolean = true

build() {
Button(this.isPause ? '暂停' : '播放')
.onClick(() => {
let context = getContext(this) as common.UIAbilityContext;
let pathDir = context.filesDir;
let path = pathDir + '/EGJDmH/trailer.mp3';
if (!this.isPause) {
if (this.isPlay) {
this.avlPlayer.avPlayerUrlDemo(path, this.isPause)
this.isPlay = !this.isPlay
} else {
this.avlPlayer.play()
}
} else {
this.avlPlayer.pause()
}
this.isPause = !this.isPause

})
}
}

path路径的EGJDmH是沙箱的文件名,我设计的功能是点击播放之后按钮变成暂停,再点击变成播放,每次暂停后再播放都是从暂停的位置播放,这样更符合实际需求。

针对HarmonyOS 鸿蒙Next中使用AVPlayer播放.wav文件时,隔一次才能正常播放的问题,这可能是由于多种因素导致的。以下是一些可能的原因及排查方向:

  1. 资源释放问题:在AVPlayer播放完成后,如果没有正确释放资源,可能导致后续播放时资源冲突或不足。确保每次播放完毕后正确调用stop()reset()release()方法释放资源。
  2. 文件加载问题:.wav文件可能在加载过程中存在问题,如文件路径错误、文件损坏或格式不兼容等。检查文件路径和文件完整性,确保文件格式与AVPlayer支持的格式匹配。
  3. API调用顺序:AVPlayer的状态机管理较为严格,API调用顺序不当可能导致播放异常。确保按照官方文档正确设置播放资源、配置参数和调用控制方法。
  4. 系统或API限制:系统对AVPlayer的创建或使用可能有特定限制,如同时创建的播放器数量限制等。查阅HarmonyOS的官方文档,了解相关限制和最佳实践。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部