文档章节

用DirectX Audio和DirectShow播放声音和音乐(7)

rise-worlds
 rise-worlds
发布于 2016/06/20 13:39
字数 2929
阅读 1
收藏 0
加入到MP3的革命中

MP3是一种音频压缩格式,它通过删除或修改音乐中不易被人耳察觉的部分来使音乐更小,占用的存储空间更少。在项目中使用MP3(.MP3文件)需要使用DirectX中的 DirectShow组件,在这个组件的帮助下,只需几行短短的代码,就能使用任意的MP3文件了(DirectShow也支持其他的媒体文件,比如 WMA,AVI,MPG等)。当然要想使用更多的媒体文件,必须已经在操作系统中安装了解码器。

解码器(codec)是一个程序,用于解码或编码一些指定的格式(比如MP3解码器专门解码.MP3文件)。通常可以从发明或者创建这种格式的公司中获取这种格式的解码器。比如,MP3解码器来自于Fraunhofer Insitute。幸运的是,MP3解码器等几种比较流行的解码器已经被集成到操作系统中(比如.mp3,.avi,.mpg等),而无需另外从 internet下载这些格式的解码器了。

要在项目中使用DirectShow,需要包含dshow.h头文件,并且在链接库中加入strmiids.lib。

使用DirectShow

DirectX是一组COM接口组件,DirectShow也不例外,DirectShow中经常使用的组件如下:

IGraphBuilder:  帮助建立滤波图,滤波过滤图是一组对象或接口的集合,用于处理某种媒体文件。
IMediaControl:控制数据在滤波图中的流程,使用该接口控制音乐的回放。
IMediaEvents:   从滤波图中获取事件及通告,当希望知道在滤波图中发生了什么的时候这个对象很有用,比如希望知道一个音乐是否仍然在播放或者已经停止播放。

其中第一个接口IGraphBuilder是比较重要的对象,其他对象都依赖于它,或者靠它创建。它创建滤波器,用于处理媒体问题,另外很多有用的功能也是依靠这个对象。

使用DirectShow播放MP3的第一步是调用 CoCreateInstance函数创建滤波图对象IGraphBuilder。

    //  initialize COM
    
//
    
//  initialize the COM library on the current thread and identifies the concurrency model as single-thread
    
//  apartment (STA).
    CoInitialize( 0 );

    
//  create the DirectMusic performance object
    
//
    
//  creates a single uninitialized object of the class associated with a specified CLSID.
     if (FAILED(CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, 
                               (
void ** ) & g_graph_builder)))
    {
        MessageBox(NULL, 
" Unable to create DirectShow Graph Builder object. " " Error " , MB_OK);
        
return  FALSE;
    }

一旦创建对象IGraphBuilder成功,就可以请求另两个接口了:

//  Query for the media control and event objects
g_graph_builder -> QueryInterface(IID_IMediaControl, ( void ** ) & g_media_control);
g_graph_builder
-> QueryInterface(IID_IMediaEvent, ( void ** ) & g_media_event);

加载媒体文件
 
实际上, DirectShow并不加载媒体文件,而是创建一个DirectShow滤波器到文件的连接。数据在解码的时候被流化,这样可以减少在播放过程中的内存使用,创建连接的过程叫做渲染(rendering)。渲染一个文件,需要调用IGraphBuilder::RenderFile函数。

Builds a filter graph that renders the specified file.

Syntax

HRESULT RenderFile(
LPCWSTR lpwstrFile,
LPCWSTR lpwstrPlayList
);

Parameters

lpwstrFile
[in] Pointer to the name of the file containing the data to be rendered.
lpwstrPlayList
[in] Pointer to the playlist name. Reserved; must be NULL. (This parameter is currently unimplemented.)

Return Value

Returns an HRESULT value, which can include one of the following:

  • VFW_S_AUDIO_NOT_RENDERED
  • VFW_S_DUPLICATE_NAME
  • VFW_S_PARTIAL_RENDER
  • VFW_S_RPZA
  • VFW_S_VIDEO_NOT_RENDERED

Remarks

If the lpwstrPlayList parameter is NULL, this method would use the default playlist, which typically renders the entire file.

控制音乐的播放

在媒体文件被渲染之后,就可以使用另外两个接口 IMediaControl和IMediaEvent进行播放或者对播放进行控制了。

第一个接口 IMediaControl用于播放和各种播放相关的操作,这个接口有三个函数:IMediaControl::Run,IMediaControl:: Pause,IMediaControl::Stop。

如果要开始播放一段音乐,调用 IMediaControl::Run就可以了。

Switches the entire filter graph into a running state.

Syntax

HRESULT Run(void);

Return Value

Returns S_OK if the graph is actually running.

Returns S_FALSE if the graph is preparing to run (the graph will run automatically when it's ready). Call GetState to wait for the transition to the running state to complete or to check if the transition has completed. If the method returns S_FALSE, subsequent calls to GetState will return a value of State_Running when the graph is actually running. If the transition to the running state is not complete GetState can return a return code of VFW_S_STATE_INTERMEDIATE.

Returns an HRESULT error code if the graph could not run and is now stopped.

Remarks

In a running state, data is pushed down the filter graph and rendered. The graph remains in a running state until it is stopped by the IMediaControl::Pause or IMediaControl::Stop method. The graph remains in a running state even after notifying the application of completion (that is, the EC_COMPLETE notification is sent to the application). This allows the application to determine whether to pause or stop after completion.

If the filter graph is in the stopped state, this method first pauses the graph before running.

If an error value is returned, some filters within the graph might have successfully entered the running state. In a multistream graph, entire streams might be playing successfully. The application must determine whether to stop running or not.

一旦播放开始,就可以随时暂停播放或者停止播放,如果希望暂停播放,调用IMediaControl::Pause函数。

Pauses all the filters in the filter graph.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK if the graph is actually paused.

Returns S_FALSE if the graph is in paused state but some filters have not completed the transition to pause. Call GetState to wait for the transition to the paused state to complete or to check if the transition has completed. If the method returns S_FALSE, subsequent calls to GetState will return a value of State_Paused when the graph is paused. If the transition to paused is not complete GetState can return a return code of VFW_S_STATE_INTERMEDIATE.

Returns an HRESULT error code if the graph could not transition to paused state and is now stopped.

Remarks

In the paused state, filters process data but do not render it. Data is pushed down the filter graph and is processed by transform filters as far as buffering permits. No data is rendered (except that media types capable of being rendered statically, such as video, have a static, poster frame rendered in paused mode). Therefore, putting a filter graph into a paused state cues the graph for immediate rendering when put into a running state.

开始播放之后,可以随时调用IMediaContrl::Stop函数来停止播放。

Switches all filters in the filter graph to a stopped state.

Syntax

HRESULT Stop(void);

Return Value

Returns an HRESULT value.

Remarks

In this mode, filters release resources and no data is processed. If the filters are in a running state, this method pauses them before stopping them. This allows video renderers to make a copy of the current frame for poster frame display while stopped.

以下代码演示了如何播放MP3文件。

// --------------------------------------------------------------------------------
//  Play mp3 which specified by filename.
// --------------------------------------------------------------------------------
BOOL Play_MP3( char *  filename)
{
    
//  convert filename to wide-character string
    WCHAR w_filename[MAX_PATH]  =  { 0 };

    mbstowcs(w_filename, filename, MAX_PATH);

    
//  render the file
    g_graph_builder -> RenderFile(w_filename, NULL);

    
//  play the file, switches the entire filter graph into a running state.
    g_media_control -> Run();

    
return  TRUE;
}

检测播放事件

我们主要感兴趣的IMediaEvent函数大概有三个:GetEvent,FreeEventParams,WaitForCompletion。

第一个函数GetEvent可能是使用最多的函数,它用于找回通知播放状态的事件。

Retrieves the next notification event.

Syntax

HRESULT GetEvent(
long *lEventCode,
long *lParam1,
long *lParam2,
long msTimeout
);

Parameters

IEventCode
[out] Pointer to the next event notification.
lParam1
[out] Pointer to the first parameter of the event.
lParam2
[out] Pointer to the second parameter of the event.
msTimeout
[in] Time, in milliseconds, to wait before assuming that there are no events.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. If the time-out is zero and no event is waiting, or if the time-out elapses before an event appears, this method returns E_ABORT.

Remarks

The application can pass a time-out value of INFINITE to indicate that the method should block until there is an event; however, applications should avoid using INFINITE. Threads cannot process any messages while waiting in GetEvent. If you call GetEvent from the thread that processes Windows messages, specify only small wait times on the call in order to remain responsive to user input. This is most important when streaming data from a source such as the Internet, because state transitions can take significantly more time to complete.

After calling GetEvent, applications should always call FreeEventParams to release any resource associated with the event.

For a list of notification codes and event parameter values, see Event Notification Codes.

一般我们最希望获取到的事件是播放完成,这个事件的值是EC_COMPLETE。如果调用GetEvent函数之后,lEventCode的值是 EC_COMPLETE,说明播放完成了。

当获取并处理了GetEvent产生的事件后,必须把事件所占用的资源释放,释放资源使用IMediaEvent::FreeEventParams函数。

Frees resources associated with the parameters of an event.

Syntax

HRESULT FreeEventParams(
long lEventCode,
long lParam1,
long lParam2
);

Parameters

lEventCode
[in] Next event notification.
lParam1
[in] First parameter of the event.
lParam2
[in] Second parameter of the event.

Return Value

Returns an HRESULT value.

Remarks

Event parameters can be of type LONG or BSTR. If a BSTR is passed as an event, it will have been allocated by the task allocator and should be freed using this method. No reference-counted interfaces are passed to an application using IMediaEvent::GetEvent, because these cannot be overridden by IMediaEvent::CancelDefaultHandling. Therefore, do not use this method to release interfaces.

以下代码演示了如何捕捉事件并释放事件所占用的资源:

        //  get th status of the song, it if is done, exit program.

        
long  event_code, param1, param2;

        
//  retrieves the next notification event
         if (SUCCEEDED(g_media_event -> GetEvent( & event_code,  & param1,  & param2,  1 )))
        {
            
if (event_code  ==  EC_COMPLETE)
            {
                
//  frees resources associated with the parameters of an events.
                g_media_event -> FreeEventParams(event_code, param1, param2);

                
break ;
            }                
        }

在需要逐帧连续监视事件的时候,用GetEvent和FreeEventParams组合是很有用的,它能帮助我们获取事件并作恰当的处理。但当我们需要连续播放而不希望连续监视播放过程的时候,另外一个函数就会很有用,即WaitForCompletion函数。它可以一直播放,在播放完成的时候,会把控制权交给我们。

Blocks execution of the application thread until the graph's operation finishes.

Syntax

HRESULT WaitForCompletion(
long msTimeout,
long *pEvCode
);

Parameters

msTimeout
[in] Duration of the time-out, in milliseconds. Pass zero to return immediately. To block indefinitely, pass INFINITE.
pEvCode
[out] Pointer to the event that terminated the wait. This value can be one of the following:
EC_COMPLETE Operation completed.
EC_ERRORABORT Error. Playback can't continue.
EC_USERABORT User terminated the operation.
Zero Operation has not completed.

Return Value

Returns one of the following HRESULT values.

E_ABORT Function timed out before the operation completed. This is equivalent to a zero pEvCode value.
S_OK Operation completed.

Remarks

This method is the equivalent of blocking until the event notification EC_COMPLETE, EC_ERRORABORT, or EC_USERABORT is received, or the time-out occurs.

When this method returns, the filter graph is still running. This method assumes that separate calls to the IMediaEvent interface are not being made. The method fails if the graph is not in, or transitioning into, a running state.

The time-out parameter (msTimeout) specifies the length of time to wait for completion. To test whether the operation completed, specify a zero msTimeout value and check the event code value (pEvCode) for zero, indicating that the operation has not completed.

释放DirectShow资源

一旦播放完成,就要关闭和释放所有占用的DirectShow资源。

    //  stop music and relaese DirectShow objects

    
//  switches all filters in the filter graph to a stopped state.
    g_media_control -> Stop();

    g_media_event
-> Release();
    g_media_event 
=  NULL;

    g_media_control
-> Release();
    g_media_control 
=  NULL;

    g_graph_builder
-> Release();
    g_graph_builder 
=  NULL;

下面给出完整的代码示例, 由于DirectX9已经将DirectShow移除,所以需要安装DirectX8 SDK,并在Vistual Studio中设置头文件目录。

点击下载源码和工程

/* **************************************************************************************
PURPOSE:
    MP3 Playing Demo
 **************************************************************************************
*/

#include 
< windows.h >
#include 
< stdio.h >
#include 
< dshow.h >
#include 
" resource.h "

#pragma comment(lib, 
" dxguid.lib " )
#pragma comment(lib, 
" strmiids.lib " )

#pragma warning(disable : 
4996 )

#define  Safe_Release(p) if((p)) (p)->Release();

//  window handles, class.
HWND g_hwnd;
char  g_class_name[]  =   " MP3PlayClass " ;

//  DirectShows components
IGraphBuilder *   g_graph_builder  =  NULL;
IMediaControl
*   g_media_control  =  NULL;
IMediaEvent
*     g_media_event    =  NULL;

// --------------------------------------------------------------------------------
//  Play mp3 which specified by filename.
// --------------------------------------------------------------------------------
BOOL Play_MP3( char *  filename)
{
    
//  convert filename to wide-character string
    WCHAR w_filename[MAX_PATH]  =  { 0 };

    mbstowcs(w_filename, filename, MAX_PATH);

    
//  render the file
    g_graph_builder -> RenderFile(w_filename, NULL);

    
//  play the file, switches the entire filter graph into a running state.
    g_media_control -> Run();

    
return  TRUE;
}

// --------------------------------------------------------------------------------
//  Window procedure.
// --------------------------------------------------------------------------------
long  WINAPI Window_Proc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    
switch (msg)
    {
    
case  WM_DESTROY:
        PostQuitMessage(
0 );
        
return   0 ;
    }

    
return  ( long ) DefWindowProc(hwnd, msg, wParam, lParam);
}

// --------------------------------------------------------------------------------
//  Main function, routine entry.
// --------------------------------------------------------------------------------
int  WINAPI WinMain(HINSTANCE inst, HINSTANCE, LPSTR cmd_line,  int  cmd_show)
{
    WNDCLASS            win_class;
    MSG                 msg;    

    
//  create window class and register it
    win_class.style          =  CS_HREDRAW  |  CS_VREDRAW;
    win_class.lpfnWndProc   
=  Window_Proc;
    win_class.cbClsExtra    
=   0 ;
    win_class.cbWndExtra    
=  DLGWINDOWEXTRA;
    win_class.hInstance     
=  inst;
    win_class.hIcon         
=  LoadIcon(inst, IDI_APPLICATION);
    win_class.hCursor       
=  LoadCursor(NULL, IDC_ARROW);
    win_class.hbrBackground 
=  (HBRUSH) (COLOR_BTNFACE  +   1 );
    win_class.lpszMenuName  
=  NULL;
    win_class.lpszClassName 
=  g_class_name;    

    
if ( !  RegisterClass( & win_class))
        
return  FALSE;

    
//  create the main window
    g_hwnd  =  CreateDialog(inst, MAKEINTRESOURCE(IDD_MP3PLAY),  0 , NULL);

    ShowWindow(g_hwnd, cmd_show);
    UpdateWindow(g_hwnd);

    
//  initialize COM
    
//
    
//  initialize the COM library on the current thread and identifies the concurrency model as single-thread
    
//  apartment (STA).
    CoInitialize( 0 );

    
//  create the DirectMusic performance object
    
//
    
//  creates a single uninitialized object of the class associated with a specified CLSID.
     if (FAILED(CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, 
                               (
void ** ) & g_graph_builder)))
    {
        MessageBox(NULL, 
" Unable to create DirectShow Graph Builder object. " " Error " , MB_OK);
        
return  FALSE;
    }

    
//  Query for the media control and event objects
    g_graph_builder -> QueryInterface(IID_IMediaControl, ( void ** ) & g_media_control);
    g_graph_builder
-> QueryInterface(IID_IMediaEvent, ( void ** ) & g_media_event);
    
    
//  play mp3
    Play_MP3( " escape.mp3 " );
    
    
//  start message pump, waiting for signal to quit.
    ZeroMemory( & msg,  sizeof (MSG));

    
while (msg.message  !=  WM_QUIT)
    {
        
if (PeekMessage( & msg, NULL,  0 0 , PM_REMOVE))
        {
            TranslateMessage(
& msg);
            DispatchMessage(
& msg);            
        }             

        
//  get th status of the song, it if is done, exit program.

        
long  event_code, param1, param2;

        
//  retrieves the next notification event
         if (SUCCEEDED(g_media_event -> GetEvent( & event_code,  & param1,  & param2,  1 )))
        {
            
if (event_code  ==  EC_COMPLETE)
            {
                
//  frees resources associated with the parameters of an events.
                g_media_event -> FreeEventParams(event_code, param1, param2);

                
break ;
            }                
        }

        
//  frees resources associated with the parameters of an events.
        g_media_event -> FreeEventParams(event_code, param1, param2);
    }

    
//  stop music and relaese DirectShow objects

    
//  switches all filters in the filter graph to a stopped state.
    g_media_control -> Stop();

    g_media_event
-> Release();
    g_media_event 
=  NULL;

    g_media_control
-> Release();
    g_media_control 
=  NULL;

    g_graph_builder
-> Release();
    g_graph_builder 
=  NULL;

    UnregisterClass(g_class_name, inst);

    
//  release COM system
    
//
    
//  Closes the COM library on the current thread, unloads all DLLs loaded by the thread, frees any other
    
//  resources that the thread maintains, and forces all RPC connections on the thread to close.
    CoUninitialize();
    
    
return  ( int ) msg.wParam;
}

运行截图:


本文转载自:http://www.cnblogs.com/flying_bat/archive/2007/08/04/871672.html

共有 人打赏支持
rise-worlds

rise-worlds

粉丝 2
博文 1755
码字总数 0
作品 0
深圳
程序员
私信 提问
Unity3D 游戏引擎之详解游戏开发音频的播放(十五)

Unity3D 游戏引擎之详解游戏开发音频的播放 雨松MOMO原创文章如转载,请注明:转载自雨松MOMO的博客原文地址:http://blog.csdn.net/xys289187120/article/details/6989328 游戏音频的播放在任...

彭博
2012/03/09
630
0
c#播放声音文件

C#中声音的播放主要有三种方法: 1.使用API函数。 2.使用SoundPlayer类播放。 3.使用DirectX进行播放。 一、使用API函数进行播放。 windows操作系统中的winmm.dll文件中封装了声音处理的函数...

科技小毛
2017/10/19
0
0
详解游戏开发音频的播放

游戏音频的播放在任何游戏中都占据非常重要的地位,音频的播放还可以分为两种,一种为游戏音乐,另一种为游戏音效。前者适用于较长的音乐,如游戏背景音乐。第二种试用与比较短的游戏音乐,如...

jieshu
2013/08/22
133
0
请教一个android audio focus的问题

你好,我刚接触android不久,现在在学习music player ,碰到一个audio focus的问题想请教一下。 我用的android sdk是2.3,问题是出现在应用程序切换的过程中,出现了小段音乐播放的声音,比如...

张兴接
2012/04/04
1K
2
low latency playback、deep buffer playback、compressed offload playback的区别

原址 1,音频播放 Android系统audio框架中主要有三种播放模式:low latency playback、deep buffer playback和compressed offload playback。 a)low latency playback:用于按键音、游戏背景音...

慢慢的燃烧
2018/09/05
0
0

没有更多内容

加载失败,请刷新页面

加载更多

指针数组和数组指针的区别

这两个名字不同当然所代表的意思也就不同。我刚开始看到这就吓到了,主要是中文太博大精深了,整这样的简称太专业了,把人都绕晕了。从英文解释或中文全称看就比较容易理解。 指针数组:arr...

天王盖地虎626
23分钟前
0
0
Qt那些事0.0.18

今天要记一下Qt中的Resource。自我感觉理解的不错,但是还会难免有谬误,在日后有可能会更新,也有可能不会。 小声的念叨一句,女人心,海底针。 今天就直接跳过了关于QML在qrc文件中的介绍,...

Ev4n
31分钟前
0
0
深入解析js的作用域、预解析机制

虽然,ES6在我们工作中应用得越来越广泛,但是还是很多项目保留着ES5的写法,所以,今天,带着大家重新巩固下ES5下的作用域及预解析机制。 概念: 作用域:域,指的是一个空间、范围、区域,...

前端攻城老湿
34分钟前
0
0
Spring Cloud Feign - 声明式 REST Client

1、Feign是什么 声明式REST client,来自NetFlix。 允许你编写无实现代码调用REST services 替换RestTemplate(甚至更简单) Spring Cloud 为使用Feign提供了包装器 2、怎样使用Feign 对比:...

Benz001
39分钟前
2
0
前端、后端和全栈到底不该学什么

1、前言 在职业规划咨询过程中经常会被问到这样的问题: 老师,我是该深入钻研专精一门,走技术大牛路线,还是所有都要精通,做一个全栈工程师? 类似问题的变种还有,老师我是不是该30岁最迟...

前端攻城小牛
41分钟前
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部