gpt4 book ai didi

c++ - 使用 Windows 内置的 MP3 解码器播放音频?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:14:55 25 4
gpt4 key购买 nike

我如何从 C 或 C++ 使用自 Windows Media Player 6.1 以来 Windows 内置的 MP3 解码器?

我想播放 mp3 文件而不必依赖任何其他第三方库,例如 LAME.DLL。

我更新了问题以更好地符合我得到的答案,因为我非常喜欢它们。 Related question.

最佳答案

当然。与 Windows API 中的许多其他内容一样,播放 .mp3 文件的方法不止一种。以编程方式执行此操作的“最简单”方法是使用 DirectShow。 MSDN 文档甚至在恰本地称为 "How To Play a File" 的页面上包含了一个最小的代码示例。让你开始:

// Visual C++ example
#include <dshow.h>
#include <cstdio>
// For IID_IGraphBuilder, IID_IMediaControl, IID_IMediaEvent
#pragma comment(lib, "strmiids.lib")

// Obviously change this to point to a valid mp3 file.
const wchar_t* filePath = L"C:/example.mp3";

int main()
{
IGraphBuilder *pGraph = NULL;
IMediaControl *pControl = NULL;
IMediaEvent *pEvent = NULL;

// Initialize the COM library.
HRESULT hr = ::CoInitialize(NULL);
if (FAILED(hr))
{
::printf("ERROR - Could not initialize COM library");
return 0;
}

// Create the filter graph manager and query for interfaces.
hr = ::CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
IID_IGraphBuilder, (void **)&pGraph);
if (FAILED(hr))
{
::printf("ERROR - Could not create the Filter Graph Manager.");
return 0;
}

hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
hr = pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);

// Build the graph.
hr = pGraph->RenderFile(filePath, NULL);
if (SUCCEEDED(hr))
{
// Run the graph.
hr = pControl->Run();
if (SUCCEEDED(hr))
{
// Wait for completion.
long evCode;
pEvent->WaitForCompletion(INFINITE, &evCode);

// Note: Do not use INFINITE in a real application, because it
// can block indefinitely.
}
}
// Clean up in reverse order.
pEvent->Release();
pControl->Release();
pGraph->Release();
::CoUninitialize();
}

请务必通读 the DirectShow documentation了解在正确的 DirectShow 应用程序中应该发生什么。


要将媒体数据“馈送”到图形中,您需要实现一个 IAsyncReader。还好,the Windows SDK includes a sample它实现了一个名为 CAsyncReaderIAsyncReader。该示例将媒体文件读入内存缓冲区,然后使用 CAsyncReader 将数据流式传输到图形中。这可能就是你想要的。在我的机器上,示例位于文件夹 C:\Program Files\Microsoft SDKs\Windows\v7.0\Samples\multimedia\directshow\filters\async

关于c++ - 使用 Windows 内置的 MP3 解码器播放音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8121570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com