HarmonyOS鸿蒙Next中实现录音功能报错 AudioRecorderDemo---->yl test error e: {"code":5400102,"name":"BusinessError"}
HarmonyOS鸿蒙Next中实现录音功能报错 AudioRecorderDemo---->yl test error e: {“code”:5400102,“name”:“BusinessError”}
全部代码如下。点击start-开始录音按钮 会在async startRecordingProcess()走到catch方法。请问如何解决。
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { media } from '@kit.MediaKit';
import { BusinessError } from '@kit.BasicServicesKit';
class AudioRecorderDemo {
private fd: number
constructor(fd: number) {
this.fd = fd;
}
private avRecorder: media.AVRecorder | undefined = undefined;
private avProfile: media.AVRecorderProfile = {
audioBitrate: 100000, // 音频比特率
audioChannels: 2, // 音频声道数
audioCodec: media.CodecMimeType.AUDIO_AAC, // 音频编码格式,当前只支持aac
audioSampleRate: 48000, // 音频采样率
fileFormat: media.ContainerFormatType.CFT_WAV, // 封装格式,当前只支持m4a
};
getAVConfig(): media.AVRecorderConfig {
return {
audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // 音频输入源,这里设置为麦克风
profile: this.avProfile,
url: `fd://${this.fd}`, // 参考应用文件访问与管理开发示例新建并读写一个文件
};
}
// 注册audioRecorder回调函数
setAudioRecorderCallback() {
if (this.avRecorder != undefined) {
// 状态机变化回调函数
this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.log(`AudioRecorderDemo---->AudioRecorder current state is ${state}`);
})
// 错误上报回调函数
this.avRecorder.on('error', (err: BusinessError) => {
console.error(`AudioRecorderDemo---->AudioRecorder failed, code is ${err.code}, message is ${err.message}`);
})
}
}
// 开始录制对应的流程
async startRecordingProcess() {
try {
if (this.avRecorder != undefined) {
await this.avRecorder.release();
this.avRecorder = undefined;
}
// 1.创建录制实例
this.avRecorder = await media.createAVRecorder();
this.setAudioRecorderCallback();
// 2.获取录制文件fd赋予avConfig里的url;参考FilePicker文档
// 3.配置录制参数完成准备工作
await this.avRecorder.prepare(this.getAVConfig());
// 4.开始录制
await this.avRecorder.start();
} catch (e) {
console.error(`AudioRecorderDemo---->yl test error e: ${JSON.stringify(e)}`)
}
}
// 暂停录制对应的流程
async pauseRecordingProcess() {
if (this.avRecorder != undefined && this.avRecorder.state === 'started') { // 仅在started状态下调用pause为合理状态切换
await this.avRecorder.pause();
}
}
// 恢复录制对应的流程
async resumeRecordingProcess() {
if (this.avRecorder != undefined && this.avRecorder.state === 'paused') { // 仅在paused状态下调用resume为合理状态切换
await this.avRecorder.resume();
}
}
// 停止录制对应的流程
async stopRecordingProcess() {
if (this.avRecorder != undefined) {
// 1. 停止录制
if (this.avRecorder.state === 'started'
|| this.avRecorder.state === 'paused') { // 仅在started或者paused状态下调用stop为合理状态切换
await this.avRecorder.stop();
}
// 2.重置
await this.avRecorder.reset();
// 3.释放录制实例
await this.avRecorder.release();
this.avRecorder = undefined;
// 4.关闭录制文件fd
fs.close(this.fd)
}
}
// 一个完整的【开始录制-暂停录制-恢复录制-停止录制】示例
async audioRecorderDemo() {
await this.startRecordingProcess(); // 开始录制
// 用户此处可以自行设置录制时长,例如通过设置休眠阻止代码执行
await this.pauseRecordingProcess(); //暂停录制
await this.resumeRecordingProcess(); // 恢复录制
await this.stopRecordingProcess(); // 停止录制
}
}
@Entry
@Component
struct AudioPage {
@State message: string = 'Hello World';
av?: AudioRecorderDemo
atManager = abilityAccessCtrl.createAtManager();
permissions: Array<Permissions> = [
'ohos.permission.MICROPHONE',
'ohos.permission.WRITE_MEDIA',
'ohos.permission.READ_MEDIA',
'ohos.permission.MEDIA_LOCATION',
];
@State path: string = "";
async start() {
let result = await this.requestPermissions();
if (result) {
let context = getContext() as common.UIAbilityContext;
this.path = context.filesDir + "/" + "AV_" + Date.parse(new Date().toString()) + ".wav";
console.log(`path is ${this.path}`)
let file = this.createOrOpen(this.path);
this.av = new AudioRecorderDemo(file.fd)
this.av.startRecordingProcess()
}
}
createOrOpen(path: string): fs.File {
let isExist = fs.accessSync(path);
let file: fs.File;
if (isExist) {
file = fs.openSync(path, fs.OpenMode.READ_WRITE);
} else {
file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
}
return file;
}
//第1步:请求权限
async requestPermissions(): Promise<boolean> {
return await new Promise((resolve: Function) => {
try {
let context = getContext() as common.UIAbilityContext;
this.atManager.requestPermissionsFromUser(context, this.permissions)
.then(async () => {
console.log(`AudioRecorderDemo---->yl test info : ${JSON.stringify("权限请求成功")}`)
resolve(true)
}).catch(() => {
console.error(`AudioRecorderDemo---->yl test info : ${JSON.stringify("权限请求异常")}`)
resolve(false)
});
} catch (err) {
console.error(`AudioRecorderDemo---->yl test info : ${JSON.stringify("权限请求err")}` + err)
resolve(false)
}
});
}
build() {
Column() {
Button('start-开始').onClick(() => {
this.start()
})
Button('pause-暂停').onClick(() => {
this.av?.pauseRecordingProcess()
})
Button('resume-恢复').onClick(() => {
this.av?.resumeRecordingProcess()
})
Button('stop-停止').onClick(() => {
this.av?.stopRecordingProcess()
})
Button('player-播放').onClick(() => {
// todo 请实现播放方法
})
}
.margin({ top: 20, bottom: 20 })
.height('100%')
.width('100%')
.justifyContent(FlexAlign.SpaceAround)
}
}
更多关于HarmonyOS鸿蒙Next中实现录音功能报错 AudioRecorderDemo---->yl test error e: {"code":5400102,"name":"BusinessError"}的实战教程也可以访问 https://www.itying.com/category-93-b0.html
录制wav格式的音频文件,音频编码格式需要设置为AUDIO_G711MU,参考音视频录制的配置文件编码格式,AVRecorderProfile设置参数如下:
private avProfile: media.AVRecorderProfile = {
audioBitrate: 64000, // set audioBitrate according to device ability
audioChannels: 1, // set audioChannels, valid value 1-8, CFT_WAV supports 1
audioCodec: media.CodecMimeType.AUDIO_G711MU, // set audioCodec, AUDIO_G711MU matching CFT_WAV
audioSampleRate: 8000, // set audioSampleRate according to device ability
fileFormat: media.ContainerFormatType.CFT_WAV, // set fileFormat, CFT_WAV
};
更多关于HarmonyOS鸿蒙Next中实现录音功能报错 AudioRecorderDemo---->yl test error e: {"code":5400102,"name":"BusinessError"}的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
谢谢老师,
该错误代码5400102表示权限缺失。鸿蒙Next录音功能需在module.json5配置文件中声明ohos.permission.MICROPHONE权限,并在应用首次运行时动态申请用户授权。权限配置需在"module"字段的"requestPermissions"节点添加权限声明,格式需符合API 11规范。应用需使用abilityAccessCtrl的requestPermissionsFromUser方法触发授权弹窗,用户授权后方可调用AudioRecorder相关API。
错误代码5400102表示参数错误。从代码分析,问题出现在AVRecorder配置参数不匹配:
-
文件格式冲突:profile中设置fileFormat为CFT_WAV,但音频编码格式audioCodec为AUDIO_AAC。在HarmonyOS Next中,WAV容器格式通常需要PCM编码,而AAC编码对应M4A容器。
-
配置修正:将avProfile修改为:
private avProfile: media.AVRecorderProfile = {
audioBitrate: 100000,
audioChannels: 2,
audioCodec: media.CodecMimeType.AUDIO_AAC,
audioSampleRate: 48000,
fileFormat: media.ContainerFormatType.CFT_MPEG_4, // 改为MP4容器
};
- 文件扩展名同步:在AudioPage的start方法中,将文件路径扩展名改为".m4a":
this.path = context.filesDir + "/" + "AV_" + Date.parse(new Date().toString()) + ".m4a";
修改后重新测试,参数匹配后应该能正常启动录音流程。

