1 算法介绍
Opus 是IETF 标准化的开源、免专利费音频编码格式(RFC 6716),由 Xiph.Org(Vorbis/Speex 开发团队)联合 Skype 团队共同推出,2012 年正式标准化。
下面是几种算法的比较:
| 编码 | 授权 | 时延优势 | 擅长场景 | 典型缺点 |
|---|---|---|---|---|
| Opus | 免费开源 | 极低(最小 2.5ms) | 语音 + 音乐通用 | 硬件解码器普及度略低于 AAC |
| AAC | 专利(商用需授权) | 较高,帧长固定 | 音乐媒体播放 | 低码率语音表现差 |
| Speex | 开源 | 低 | 只适合语音 | 音乐音质很差,已停止维护,被 Opus 替代 |
| Vorbis | 开源 | 中等 | 音乐 | 语音性能一般,最低时延不如 Opus |
| MP3 | 专利过期 | 中等 | 媒体音频 | 低码率语音质量差 |
最大特色是Opus 内部融合两套编码模式,编码器自动切换,也可手动强制:
- CELT(频域编码):适合音乐、高音质音频;类似 Vorbis,基于 MDCT 变换;
- SILK(线性预测编码 LPC):源自 Skype,专门优化人声语音;类似 Speex。 编码器根据带宽、码率、音频内容动态混合两种模式,兼顾语音清晰度与音乐保真度。
几个关键参数:
- 采样率:支持 8kHz / 12kHz / 16kHz / 24kHz / 48kHz(最高 48kHz 全频)
- 声道:单声道、立体声;
- 码率范围:6 kbps ~ 510 kbps
- 6~20kbps:窄带语音(对讲机、低带宽语音)
- 20~64kbps:宽带语音(VoIP、通话)
- 64kbps 以上:音乐、高保真音频
- 帧长(时延关键参数!)可选:2.5ms / 5ms / 10ms / 20ms / 40ms / 60ms
2 Opus的使用(树莓派为例)
2.1 一般命令
sudo apt update
sudo apt install opus-tools ffmpeg -y
opusenc --bitrate 32 input.wav output.opus
opusdec input.opus output.wav
2.2 ALSA命令
# 从 ALSA 麦克风捕获 raw PCM 数据并直接打入 opusenc 管道
arecord -f S16_LE -r 48000 -c 1 -t raw | opusenc --raw --raw-rate 48000 - output.opus
2.3 libopus
#include <stdio.h> #include <opus/opus.h> #define SAMPLE_RATE 48000 #define CHANNELS 1 #define FRAME_SIZE 960 // 20ms @ 48kHz int main() { int error; // 1. 创建编码器 OpusEncoder *encoder = opus_encoder_create(SAMPLE_RATE, CHANNELS, OPUS_APPLICATION_VOIP, &error); if (error != OPUS_OK) { printf("Failed to create encoder: %s\n", opus_strerror(error)); return -1; } // 动态调整码率 (例如设为 32 kbps) opus_encoder_ctl(encoder, OPUS_SET_BITRATE(32000)); opus_int16 pcm_buffer[FRAME_SIZE]; // 输入的 PCM 采样数据 unsigned char opus_out[512]; // 输出的压缩 Buffer // 2. 执行编码 (返回值为压缩后的实际字节数) int encoded_bytes = opus_encode(encoder, pcm_buffer, FRAME_SIZE, opus_out, sizeof(opus_out)); printf("Encoded frame size: %d bytes\n", encoded_bytes); // 3. 销毁编码器 opus_encoder_destroy(encoder); return 0; }2.4 GStreamer使用
发送
gst-launch-1.0 alsasrc ! audioconvert ! audioresample ! \
opusenc bitrate=32000 ! rtpopuspay ! \
udpsink host=192.168.1.100 port=5000
接收
gst-launch-1.0 udpsrc port=5000 caps="application/x-rtp, media=audio, clock-rate=48000, encoding-name=OPUS" ! \
rtpopusdepay ! opusdec ! autoaudiosink