2016-09-14 748 views
1

我使用FFmpeg库进行个人项目,我需要关于一件事的帮助。我有立体声音乐文件,我想将此立体声转换为单声道音效?这个库有可能吗?有内部的功能来完成这项工作吗?我的项目是C/C++。如何使用FFmpeg将立体声转换为单声道?

我在FFmpeg网站的Doxygen文档上搜索了这个论坛,但是我没有找到有趣的东西。

感谢您的阅读!

+0

正如我记得没有功能,但你可以很容易地转换它自己通过计算两个流在一起。 – user1810087

+0

你有没有任何代码给例子? – Meugiwara

回答

3

使用swr_convert从libswresample到格式之间进行转换。就像:

#include "libswresample/swresample.h" 

au_convert_ctx = swr_alloc(); 

out_channel_layout = AV_CH_LAYOUT_MONO; 
out_sample_fmt = AV_SAMPLE_FMT_S16; 
out_sample_rate = 44100; 
out_channels = av_get_channel_layout_nb_channels(out_channel_layout); 

in_sample_fmt = pCodecCtx->sample_fmt; 
in_channel_layout=av_get_default_channel_layout(pCodecCtx->channels); 

au_convert_ctx=swr_alloc_set_opts(au_convert_ctx,out_channel_layout, out_sample_fmt, out_sample_rate, 
      in_channel_layout, in_sample_fmt, pCodecCtx->sample_rate, 0, NULL); 
swr_init(au_convert_ctx); 
//Generate your frame of original audio, then use swr_convert to convert to mono, 
//converted number of samples will now be in out_buffer. 
int converted = swr_convert(au_convert_ctx, &out_buffer, MAX_AUDIO_FRAME_SIZE, (const uint8_t **)&pFrame->data , pFrame->nb_samples); 
//... 
swr_free(&au_convert_ctx); 

为了让你开始。这将转换任何原始格式到44100 kHz单声道。您也可以使用pCodecCtx->sample_rate作为输出采样率。

这是最灵活和最简单的解决方案。

0

正如我在评论中提到的那样,您可以自己重新采样。这取决于你已经拥有的和你使用的格式,所以我不能给你即时运行的代码,但我可以给你一个例子(伪/真实代码混合)。

在对帧进行编码并完成了必须完成的操作之后,数据缓冲区中将填充音频。现在取决于您的格式(请参阅here)以及您拥有多少个频道。让我们假设它是16位签署立体声,比你的缓冲会是什么样子:

+-----+-----+-----+-----+-----+ 
| LS1 | RS1 | LS2 | RS2 | ... | 
+-----+-----+-----+-----+-----+ 
// LS = LEFT SAMPLE 16 Bit 
// RS = RIGHT SAMPLE 16 Bit 

现在通过缓冲迭代并一起计算左,右样品。

for(int i=0; i<sample_size; i+=2) { 
    auto r = (static_cast<int32_t>(buffer[i]) + buffer[i+1])/2; 
    buffer[i] = buffer[i+1] = r; 
} 

就是这样......

相关问题