You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native录音输出格式异常:无法生成ogg/opus格式

解决React Native录制音频强制输出MP4的问题

单纯修改文件扩展名不会改变实际的音频编码和容器格式,问题根源在于RN音频库默认调用的原生录音API使用了MP4作为输出格式。以下是可行的解决方法:

1. 配置原生编码参数(针对现有库)

不管用react-native-audio还是react-native-audio-record-player,都需要在初始化录音时指定正确的编码和容器格式,而非仅修改文件名:

Android 端配置

Android 5.0及以上支持Opus编码,初始化时明确设置编码和输出格式:

import { AudioRecorder } from 'react-native-audio';

// 示例配置(输出Opus格式)
await AudioRecorder.prepareRecordingAtPath('/sdcard/my-recording.opus', {
  SampleRate: 44100,
  Channels: 1,
  AudioQuality: 'High',
  AudioEncoding: 'opus', // 指定Opus编码
  OutputFormat: 'ogg'    // 匹配OGG容器
});

iOS 端配置

iOS原生AVFoundation对Opus的支持有限,需指定对应的格式ID:

await AudioRecorder.prepareRecordingAtPath('/Documents/my-recording.opus', {
  AVFormatIDKey: 'com.apple.coreaudio.format.opus',
  SampleRate: 48000,
  NumberOfChannels: 1,
  AudioQuality: 'High'
});

如果iOS端配置后仍无效,建议集成第三方Opus编码库(如libopus)来实现稳定录制。

2. 更换为支持OGG/Opus的专用RN库

现有库的格式支持可能有限,试试专门针对Opus的录音库:

  • react-native-opus-recorder:直接输出Opus格式,无需额外配置
  • react-native-sound-recorder:支持更多编码选项,部分版本可输出OGG/Opus

以react-native-opus-recorder为例的使用代码:

import OpusRecorder from 'react-native-opus-recorder';

// 开始录制
await OpusRecorder.start({
  path: '/path/to/recording.opus',
  sampleRate: 48000,
  channels: 1,
  bitrate: 64000
});

// 停止录制
await OpusRecorder.stop();

3. 自定义原生录音模块

如果RN库无法满足需求,可以手动封装原生模块:

  • Android:使用MediaRecorder类,设置setAudioEncoder(MediaRecorder.AudioEncoder.OPUS)和setOutputFormat(MediaRecorder.OutputFormat.OGG),再封装为RN可用的接口
  • iOS:集成libopus库,直接用Opus编码器处理音频数据,写入OGG容器后暴露给RN调用

4. 后期转码作为备选方案

如果无法直接录制目标格式,可先录制MP4,再用转码库转换为OGG/Opus:

import AudioTranscoder from 'react-native-audio-transcoder';

const isSuccess = await AudioTranscoder.transcode(
  '/path/to/input.mp4',
  '/path/to/output.opus',
  {
    bitrate: 64000,
    sampleRate: 48000,
    channels: 1,
    format: 'opus'
  }
);

内容的提问来源于stack exchange,提问作者Karthikeyan Ravichandran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 14:05:25