本人写过ffmpeg读取系统声音,生成音频原始流pcm文件
文中定义的channel_layout 为AV_CH_LAYOUT_STEREO,即左右通道的双通道,现在将这个双通道文件拆解成左右两个通道文件。
本文的双通道文件的采样位数是16,即双字节,其存储对于下面的第四个。
故拆解变得比较简单,如下所示:
void CSeparateTwoChannel::StartSeparate(const char *pPcmFile, const char *pLeftChannelFile, const char *pRightChannelFile){fpPcm = fopen(pPcmFile, "rb");fpLeftChannel = fopen(pLeftChannelFile, "wb");fpRightChannel = fopen(pRightChannelFile, "wb");int iReaded = 0;char szPcm[4] = {0 };while (1){iReaded = fread(&szPcm, 4, 1, fpPcm);if (iReaded <= 0){break;}fwrite(szPcm, 2, 1, fpLeftChannel);fwrite(szPcm + 2, 2, 1, fpRightChannel);}fclose(fpPcm);fclose(fpLeftChannel);fclose(fpRightChannel);}
代码结构如下:
其中SeparateTwoChannelToOneChannel.cpp的代码如下:
// SeparateTwoChannelToOneChannel.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。//#include <iostream>#include <stdio.h>#include "SeparateTwoChannel.h"int main(){const char *pFilePcm = "E:\\learn\\ffmpeg\\FfmpegGeneratePcm\\x64\\Release\\pcm_inner_audio_feiniao_2channel.pcm";const char *pFileLeftChannel = "E:\\learn\\ffmpeg\\FfmpegGeneratePcm\\x64\\Release\\pcm_inner_audio_feiniao_2channel_leftchannel.pcm";const char *pFileRightChannel = "E:\\learn\\ffmpeg\\FfmpegGeneratePcm\\x64\\Release\\pcm_inner_audio_feiniao_2channel_rightchannel.pcm";CSeparateTwoChannel cSeparateTwoChannel;cSeparateTwoChannel.StartSeparate(pFilePcm, pFileLeftChannel, pFileRightChannel);return 0;}
SeparateTwoChannel.h的代码如下:
#pragma once#include <Windows.h>#include <stdio.h>class CSeparateTwoChannel{public:CSeparateTwoChannel();~CSeparateTwoChannel();public:void StartSeparate(const char *pPcmFile, const char *pLeftChannelFile, const char *pRightChannelFile);private:FILE *fpPcm = NULL;FILE *fpLeftChannel = NULL;FILE *fpRightChannel = NULL;};
SeparateTwoChannel.cpp的代码如下:
#include "SeparateTwoChannel.h"CSeparateTwoChannel::CSeparateTwoChannel(){}CSeparateTwoChannel::~CSeparateTwoChannel(){}void CSeparateTwoChannel::StartSeparate(const char *pPcmFile, const char *pLeftChannelFile, const char *pRightChannelFile){fpPcm = fopen(pPcmFile, "rb");fpLeftChannel = fopen(pLeftChannelFile, "wb");fpRightChannel = fopen(pRightChannelFile, "wb");int iReaded = 0;char szPcm[4] = {0 };while (1){iReaded = fread(&szPcm, 4, 1, fpPcm);if (iReaded <= 0){break;}fwrite(szPcm, 2, 1, fpLeftChannel);fwrite(szPcm + 2, 2, 1, fpRightChannel);}fclose(fpPcm);fclose(fpLeftChannel);fclose(fpRightChannel);}
如果觉得《双声道pcm文件拆解成左右两个单声道文件》对你有帮助,请点赞、收藏,并留下你的观点哦!