通过命令获取音视频设备列表:
ffmpeg -list_devices true -f dshow -i dummy
搜狗截图20200617200342.png
代码实现音频列表的获取 pcm数据的采集
#define __STDC_CONSTANT_MACROS
extern "C"
{
#include <libavutil/log.h>
#include <libavdevice/avdevice.h>
#include <libavformat/avformat.h>
}
#include <windows.h>
#include <vector>
#include <string>
#include <memory>
#pragma comment(lib, "avutil.lib")
#pragma comment(lib, "avdevice.lib")
#pragma comment(lib, "avformat.lib")
#pragma comment(lib, "avcodec.lib")
#pragma comment(lib, "Winmm.lib")
using std::vector;
using std::string;
using std::shared_ptr;
void capture_audio()
{
//windows api 获取音频设备列表(ffmpeg 好像没有提供获取音视频设备的api)
int nDeviceNum = waveInGetNumDevs();
vector<string> vecDeviceName;
for (int i = 0; i < nDeviceNum; ++i)
{
WAVEINCAPS wic;
waveInGetDevCaps(i, &wic, sizeof(wic));
//转成utf-8
int nSize = WideCharToMultiByte(CP_UTF8, 0, wic.szPname, wcslen(wic.szPname), NULL, 0, NULL, NULL);
shared_ptr<char> spDeviceName(new char[nSize + 1]);
memset(spDeviceName.get(), 0, nSize + 1);
WideCharToMultiByte(CP_UTF8, 0, wic.szPname, wcslen(wic.szPname), spDeviceName.get(), nSize, NULL, NULL);
vecDeviceName.push_back(spDeviceName.get());
av_log(NULL, AV_LOG_DEBUG, "audio input device : %s \n", spDeviceName.get());
}
if (vecDeviceName.size() <= 0)
{
av_log(NULL, AV_LOG_ERROR, "not find audio input device.\n");
return;
}
string sDeviceName = "audio=" + vecDeviceName[0];//使用第一个音频设备
//ffmpeg
avdevice_register_all(); //注册所有输入输出设备
AVInputFormat* ifmt = av_find_input_format("dshow"); //设置采集方式 dshow
if (ifmt == NULL)
{
av_log(NULL, AV_LOG_ERROR, "av_find_input_format for dshow fail.\n");
return;
}
AVFormatContext* fmt_ctx = NULL; //format 上下文
int ret = avformat_open_input(&fmt_ctx, sDeviceName.c_str(), ifmt, NULL); //打开音频设备
if (ret != 0)
{
av_log(NULL, AV_LOG_ERROR, "avformat_open_input fail. return %d.\n", ret);
return;
}
AVPacket pkt;
FILE* fp = fopen("dst.pcm", "wb");
int count = 0;
while (count++ < 10)
{
ret = av_read_frame(fmt_ctx, &pkt);
if (ret != 0)
{
av_log(NULL, AV_LOG_ERROR, "av_read_frame fail, return %d .\n", ret);
break;
}
fwrite(pkt.data, 1, pkt.size, fp);
av_packet_unref(&pkt);//必须释放pkt申请的内存,否则会内存泄露
}
fflush(fp);//刷新文件io输出缓冲区
fclose(fp);
avformat_close_input(&fmt_ctx);
}
int main(int argc, char** argv)
{
av_log_set_level(AV_LOG_DEBUG); //设置ffmpeg日志库等级
capture_audio();
Sleep(1);
}
设置音频输出驱动并使用ffplay 进行播放
命令:
set SDL_AUDIODRIVER=directsound
//设置可用的音频输出驱动
ffplay -ar 44100 -channels 2 -f s16le -i dst.pcm
//使用ffplay 命令 进行播放
2.png