我正在編寫使用DirectShow庫在C#中捕獲音頻並將其寫入ogg容器的程序。我在GraphEditPlus中創建了一個圖表。它生成一個GraphBuilder方法代碼,我將其複製到我的代碼中。此代碼是:使用DirectShow捕獲音頻
class AudioCapture
{
public static void checkHR(int hr, string msg)
{
if (hr < 0)
{
MessageBox.Show(msg);
DsError.ThrowExceptionForHR(hr);
}
}
public static void BuildGraph (IGraphBuilder pGraph, string dstFile)
{
int hr = 0;
//graph builder
ICaptureGraphBuilder2 pBuilder = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
hr = pBuilder.SetFiltergraph(pGraph);
checkHR(hr, "Can't SetFiltergraph");
Guid CLSID_XiphOrgVorbisEncoder = new Guid("{5C94FE86-B93B-467F-BFC3-BD6C91416F9B}");
Guid CLSID_XiphOrgOggMuxer = new Guid("{1F3EFFE4-0E70-47C7-9C48-05EB99E20011}");
//add microphone
IBaseFilter pMicrophone = (IBaseFilter) new AudioRecord();
hr = pGraph.AddFilter(pMicrophone, "Microphone");
checkHR(hr, "Can't add microphone to graph");
//add Vorbis Encoder
IBaseFilter pVorbisEncoder = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_XiphOrgVorbisEncoder));
checkHR(hr, "Can't add Vorbis Encoder to graph");
//connect Microphone and Vorbis Encoder
hr = pGraph.ConnectDirect(GetPin(pMicrophone, "Capture"), GetPin(pVorbisEncoder, "PCM In"), null);
checkHR(hr, "Can't connect Microphone and Vorbis Encoder");
//add Ogg Muxer
IBaseFilter pOggMuxer = (IBaseFilter)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID_XiphOrgOggMuxer));
checkHR(hr, "Can't add Ogg Muxer to graph");
//set destination filename
IFileSinkFilter pOggMuxer_sink = pOggMuxer as IFileSinkFilter;
if (pOggMuxer_sink == null)
checkHR(unchecked((int)0x80004002), "Can't get IFileSinkFilter");
hr = pOggMuxer_sink.SetFileName(dstFile, null);
checkHR(hr, "Can't set filename");
//connect Vorbis Encoder and Ogg Muxer
hr = pGraph.ConnectDirect(GetPin(pVorbisEncoder, "VorbisOut"), GetPin(pOggMuxer, "Ogg Packet In"), null);
checkHR(hr, "Can't connect Vorbis Encoder and Ogg Muxer");
}
static IPin GetPin(IBaseFilter filter, string pinname)
{
IEnumPins epins;
int hr = filter.EnumPins(out epins);
checkHR(hr, "Can't enumerate pins");
IntPtr fetched = Marshal.AllocCoTaskMem(4);
IPin[] pins = new IPin[1];
while (epins.Next(1, pins, fetched) == 0)
{
PinInfo pinfo;
pins[0].QueryPinInfo(out pinfo);
bool found = (pinfo.name == pinname);
DsUtils.FreePinInfo(pinfo);
if (found)
return pins[0];
}
checkHR(-1, "Pin not found");
return null;
}
}
當我試圖執行該代碼程序拋出我的消息「品無法找到」試圖連接麥克風和Vorbis編碼器過濾後。調試後,我發現它找不到麥克風引腳。有誰知道我的錯誤在哪裏?
最好搜索音頻輸入設備。只是'新的AudioRecord()'不會自動創建micropone輸入。 – wimh
嗨如何錄製視頻和音頻並將其保存到一個視頻文件?我可以通過分離文件來完成。你能幫我嗎。 – Vijayaraghavan