播放WAV文件

来源:互联网 发布:php js实现秒杀倒计时 编辑:程序博客网 时间:2024/05/01 16:42
播放WAV文件

播放一个wav文件要比想象中容易很多,因为很多事情都交给了系统。在这个工程中CSoundPlayer实现了播放wav文件的必要步骤

[Copy to clipboard]
CODE:
#include <MdaAudioSamplePlayer.h>
class CSoundPlayer: public CBase, public MMdaAudioPlayerCallback
{
public:
   static CSoundPlayer* NewL(const TDesC& aFile);
   static CSoundPlayer* NewLC(const TDesC& aFile);
   ~CSoundPlayer();
   void PlayL();
   void StopL();

   //
   // 来自 MMdaAudioPlayerCallback
   //
   void MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration);
   void MapcPlayComplete(TInt aError);

private:
   CSoundPlayer();
   void ConstructL(const TDesC& aFile);

private:
   enum TState
   {
       ENotReady,
       EReady,
       EPlaying
   };

   TState iState;
   CMdaAudioPlayerUtility* iMdaPlayer;
};

关键类:
CMdaAudioPlayerUtility : 实现了解码,CSoundPlayer有一个私有的CMdaAudioPlayerUtility类型的成员iMdaPlayer.
MMdaAudioPlayerCallback: 是iMdaPlayer的观察者(用于观察播放器中发生的时间,比如初始化结束和播放结束等)。这个类最少要实现MapcInitComplete() 和MapcPlayComplete() ,我们下面讲要讲到。

初始化播放器
CSoundPlayer::NewL() 或者 CSoundPlayer::NewLC()用于来初始化播放器,二阶构造函数将调用CMdaAudioPlayerUtility::NewFilePlayerL()来初始化iMdaPlayer .

[Copy to clipboard]
CODE:
void CSoundPlayer::ConstructL(const TDesC& aFile)
{
//
// Create a file audio player utility instance
//
iMdaPlayer=CMdaAudioPlayerUtility::NewFilePlayerL(aFile,*this);
}

还有一种构造函数,CMdaAudioPlayerUtility::NewDesPlayerL() 用于wav已经在ram内存中的情况

到现在为止,播放器还不能开始播放。实际上,如果你尝试在NewFilePlayerL()后立刻调用iMdaPlayer->PlayL() ,可能你会听不到任何东西,因为只有播放器实例构造完全结束以后才可以播放。
播放器初始话结束以后,框架会调用MapcInitComplete()。两种常见的实现方式如下:

[Copy to clipboard]
CODE:
//
// 方法 1: 设置iState设置为准备状态,通知播放器已经准备好了
//
void CSoundPlayer::MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& /*aDuration*/)
{
   iState = aError ? ENotReady : EReady;
}



[Copy to clipboard]
CODE:
//
// 方法 2: 立刻播放文件
//
void CSoundPlayer::MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& /*aDuration*/)
{
   if (!aError)
       iMdaPlayer->PlayL();
}

播放文件
一旦初始化结束,就像上面的例子一样,回调函数中调用了CMdaAudioPlayerUtility::PlayL()。在Sound1 例子中,这里使用的是CSoundPlayer::PlayL()

[Copy to clipboard]
CODE:
void CSoundPlayer::Play()
{
   if(iState==EReady)
   {
       iState=EPlaying;
       iMdaPlayer->Play();
   }
}

播放结束后,框架将调用MapcPlayComplete(),下面Sound1的实现部分

[Copy to clipboard]
CODE:
void CSoundPlayer::MapcPlayComplete(TInt aError)
{
   iState = aError ? ENotReady : EReady;
}

如果要想运行这个例子,你必须把一个play.wav放在C:/System/Apps/Sound/下  (模拟器放在C:/Symbian/6.1/Series60/Epoc32/Wins/c/system/apps/Sound )