鸿蒙Next如何实现录音并保存为mp3文件
在鸿蒙Next开发中,如何实现录音功能并将录音保存为MP3格式的文件?需要哪些API和权限配置?能否提供具体的代码示例或实现步骤?
2 回复
鸿蒙Next录音转MP3?简单!用AudioCapturer抓声音,再用Mp3Writer编码保存。记得申请麦克风权限,不然用户会以为你在演哑剧。代码写两行,调试一整天——程序员日常罢了!
更多关于鸿蒙Next如何实现录音并保存为mp3文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next(HarmonyOS NEXT)中,可以通过AudioCapturer实现录音,并使用第三方库(如LAME)将PCM数据转换为MP3格式。以下是实现步骤和示例代码:
1. 添加权限
在module.json5中声明音频录制权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.MICROPHONE"
}
]
}
}
2. 实现录音和MP3编码
import audio from '@ohos.multimedia.audio';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// 初始化AudioCapturer配置
let audioStreamInfo: audio.AudioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
};
let audioCapturerInfo: audio.AudioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0
};
let audioCapturerConfig: audio.AudioCapturerConfig = {
audioStreamInfo: audioStreamInfo,
audioCapturerInfo: audioCapturerInfo
};
// 创建临时PCM文件和最终MP3文件路径
let pcmPath: string = '临时PCM文件路径.pcm';
let mp3Path: string = '最终MP3文件路径.mp3';
// 初始化LAME编码器(需自行集成Native LAME库)
// 假设已通过NAPI封装LAME方法
let lameWrapper = requireNativeModule('lame-wrapper');
export class AudioRecorder {
private audioCapturer: audio.AudioCapturer | null = null;
private isRecording: boolean = false;
// 开始录音
async startRecording(): Promise<void> {
try {
this.audioCapturer = await audio.createAudioCapturer(audioCapturerConfig);
await this.audioCapturer.start();
this.isRecording = true;
// 创建PCM文件
let pcmFile = fs.openSync(pcmPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// 实时读取音频数据并写入文件
while (this.isRecording) {
let buffer = await this.audioCapturer.read(4096, true);
fs.writeSync(pcmFile.fd, buffer);
}
fs.closeSync(pcmFile);
} catch (err) {
console.error(`录音失败: ${(err as BusinessError).message}`);
}
}
// 停止录音并转换格式
async stopRecording(): Promise<void> {
if (!this.audioCapturer) return;
this.isRecording = false;
await this.audioCapturer.stop();
this.audioCapturer.release();
// 调用LAME将PCM转换为MP3
try {
lameWrapper.encodePcmToMp3(pcmPath, mp3Path, 44100, 1, 128);
console.log(`MP3文件已保存: ${mp3Path}`);
// 删除临时PCM文件
fs.unlinkSync(pcmPath);
} catch (err) {
console.error(`格式转换失败: ${(err as BusinessError).message}`);
}
}
}
3. 使用示例
let recorder = new AudioRecorder();
// 开始录音
recorder.startRecording();
// 10秒后停止并保存
setTimeout(() => {
recorder.stopRecording();
}, 10000);
注意事项:
- LAME库集成:需要自行通过NAPI封装LAME的C/C++库到鸿蒙项目中
- 文件路径:确保应用有读写存储空间的权限
- 错误处理:实际使用时需完善异常处理逻辑
- 性能优化:大数据量录音建议使用流式处理,避免内存溢出
此方案通过原生录音结合第三方编码库实现MP3输出,兼顾了音频质量和格式通用性。

