Playing audio files

本文介绍了一个音频播放器的实现细节,包括播放、停止、设置音量等功能,并通过状态观察者模式来更新播放状态。

 

AudioPlayer.cpp

#include <Mda/Common/Resource.h>

#include <BAUTILS.H>

  

CAudioPlayer* CAudioPlayer::NewL(MExamplePlayStateObserver& aObserver)

    {

    CAudioPlayer* self = CAudioPlayer::NewLC(aObserver);

    CleanupStack::Pop(self);

    return self;

    }

 

 

CAudioPlayer* CAudioPlayer::NewLC(MExamplePlayStateObserver& aObserver)

    {

    CAudioPlayer* self = new (ELeave) CAudioPlayer(aObserver);

    CleanupStack::PushL(self);

    self->ConstructL();

    return self;

    }

 

 

CAudioPlayer::CAudioPlayer(MExamplePlayStateObserver& aObserver)

:iObserver(aObserver),iVolume(5)

    {

 

    }

 

 

CAudioPlayer::~CAudioPlayer()

{

          delete iExampleTimer;

 

    if(iPlayerUtility)

    {

           iPlayerUtility->Stop();

           iPlayerUtility->Close();

    }

 

    delete iPlayerUtility;

}

 

void CAudioPlayer::ConstructL()

{

          iExampleTimer = CExampleTimer::NewL(CActive::EPriorityStandard,*this);

 

          ReportStateAndTime();

}

 

void CAudioPlayer::TimerExpired(TAny* /*aTimer*/,TInt aError)

{

          // update states first.

          ReportStateAndTime();

 

          if(iExampleTimer && aError != KErrCancel)         

          {

                    iExampleTimer->After(KReFreshTimeOut);

          }

}

 

 

void CAudioPlayer::PlayL(const TDesC& aFileName)

{

          iCurrentFile.iName.Copy(aFileName);

 

          if(iExampleTimer)  

          {

                    iExampleTimer->Cancel();

          }

 

          if(iPlayerUtility)

    {

           iPlayerUtility->Stop(); // stop any play/rec

           iPlayerUtility->Close();// close previously opened file.

    }

 

          delete iPlayerUtility;           // and then we can delete it.

          iPlayerUtility = NULL;

          iPlayerUtility = CMdaAudioRecorderUtility::NewL(*this);

    iPlayerUtility->OpenFileL(iCurrentFile.iName);

 

          if(iExampleTimer)  

          {

                    iExampleTimer->After(KReFreshTimeOut);

          }

}

 

void CAudioPlayer::StopL(void)

{

          if(iExampleTimer)

          {

                    iExampleTimer->Cancel();

          }

 

    if(iPlayerUtility)

    {

           iPlayerUtility->Stop();

    }

 

    ReportStateAndTime();

}

 

void CAudioPlayer::SetVolume(TInt& aVolume)

{

          if(aVolume < 1)

                    aVolume = 1;

          else if(aVolume > 10)

                    aVolume = 10;

 

          iVolume = aVolume;// save to internal value always

          if(iPlayerUtility) // and if utility exists, set it to it as well.

          {

                    TInt Vol = ((iPlayerUtility->MaxVolume() * iVolume) / 10);

                    iPlayerUtility->SetVolume(Vol);

          }

}

 

 

void CAudioPlayer::ReportStateAndTime(void)

{

          TInt CurrPosition(0),FileDuration(0);

 

          CMdaAudioClipUtility::TState CurrState(CMdaAudioClipUtility::ENotReady);

 

          if(iPlayerUtility)

          {

                    CurrState =  iPlayerUtility->State();

 

                    TInt64 HelpPos = iPlayerUtility->Position().Int64();        

                    // micro seconds, thus lets make it seconds for UIs

                    CurrPosition = HelpPos / 1000000;

 

                    // and with playing its the file duration.

                    HelpPos = iPlayerUtility->Duration().Int64();     

                    FileDuration = HelpPos / 1000000;

          }

 

          // update valus to the UI

          iObserver.StateUpdate(CurrState,CurrPosition,FileDuration);

}

 

 

void CAudioPlayer::MoscoStateChangeEvent(CBase* aObject, TInt aPreviousState, TInt aCurrentState, TInt /*aErrorCode*/)

{

          if(aObject == iPlayerUtility)

          {

                    ReportStateAndTime();

 

                    switch(aCurrentState)

                    {

                    case CMdaAudioClipUtility::EOpen:

                               {

                                         // only when first opening files.

                                         // also called with aCurrentState == EOpen, when

                                         // playing or recording finishes.

                                         if(aPreviousState == CMdaAudioClipUtility::ENotReady)

                                         {

                                                   TInt Vol = ((iVolume * iPlayerUtility->MaxVolume()) / 10);

                                                   iPlayerUtility->SetVolume(Vol);

 

                                                   TRAPD(err,iPlayerUtility->PlayL(););

                                         }

                               }

                               break;

                    case CMdaAudioClipUtility::EPlaying:

                    case CMdaAudioClipUtility::ERecording:

                    case CMdaAudioClipUtility::ENotReady:

                    default: // no need to do anything on these states.

                               break;

                    }

          }

}

 

 

AudioPlayer.h

#include <MdaAudioSampleEditor.h>

#include <Mda/Client/Utility.h>

#include "CExampleTimer.h"

 

const TInt          KReFreshTimeOut = 1000000; // re-fresh every second

//

class MExamplePlayStateObserver

          {

          public:

                    virtual void StateUpdate(CMdaAudioClipUtility::TState aState, TInt aPosition, TInt aDuration)=0;

          };

 

 

class CAudioPlayer : public CBase, public MMdaObjectStateChangeObserver,MExampleTimerNotify

    {

public:

    static CAudioPlayer* NewL(MExamplePlayStateObserver& aObserver);

    static CAudioPlayer* NewLC(MExamplePlayStateObserver& aObserver);

     ~CAudioPlayer();

public:  // public functions

    void PlayL(const TDesC& aFileName);

          void StopL(void);

          void SetVolume(TInt& aVolume);

protected: // from MMdaObjectStateChangeObserver & MExampleTimerNotify

          void MoscoStateChangeEvent(CBase* aObject, TInt aPreviousState, TInt aCurrentState, TInt aErrorCode);

          void TimerExpired(TAny* aTimer,TInt aError);

private:// interna functions

          void ReportStateAndTime(void);

    void ConstructL();

    CAudioPlayer(MExamplePlayStateObserver& aObserver);      

private:

          MExamplePlayStateObserver&               iObserver;

          CMdaAudioRecorderUtility*                iPlayerUtility;

    TInt                                                                iVolume;

    TMdaFileClipLocation                            iCurrentFile;

    CExampleTimer*                                            iExampleTimer;

};

 

 

PlayUtility.cpp

#include <MdaAudioTonePlayer.h>

#include <eikmenup.h>

 

 

CPlayerUtility* CPlayerUtility::NewL(const TDesC& aFileName)

{

    CPlayerUtility* self = NewLC(aFileName);

    CleanupStack::Pop(self); 

    return self;

}

 

CPlayerUtility* CPlayerUtility::NewLC(const TDesC& aFileName)

{

    CPlayerUtility* self = new (ELeave) CPlayerUtility();

    CleanupStack::PushL(self);

    self->ConstructL(aFileName);

    return self;

}

 

CPlayerUtility::~CPlayerUtility()

{

          if(iPlayUtility)

          {

                    iPlayUtility->Stop();

                    iPlayUtility->Close();

          }

 

    delete iPlayUtility;

}

 

CPlayerUtility::CPlayerUtility()

{

}

 

void CPlayerUtility::ConstructL(const TDesC& aFileName)

{

    iPlayUtility = CMdaAudioPlayerUtility::NewFilePlayerL(aFileName, *this);

          iPlaying = iPrepared = EFalse;

}

 

void CPlayerUtility::Play()

{

          iPlayUtility->Play();

          iPlaying = ETrue;

}

 

void CPlayerUtility::Stop()

{

          iPlayUtility->Stop();

          iPlaying = EFalse;

}

 

 

void CPlayerUtility::MapcPlayComplete(TInt /*aError*/)

{

          iPlaying = EFalse;

}

 

void CPlayerUtility::MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& /*aDuration*/)   

{

          if(aError == KErrNone)

          {

                    iPrepared = ETrue;

                    iPlayUtility->SetVolume(iPlayUtility->MaxVolume());         

                iPlayUtility->Play();

          }

}

 

PlayUtility.h

#include <e32std.h>

#include <MdaAudioSamplePlayer.h>

 

class CPlayerUtility : public CBase, public MMdaAudioPlayerCallback

    {

public:

    static CPlayerUtility* NewL(const TDesC& aFileName);

    static CPlayerUtility* NewLC(const TDesC& aFileName);

    ~CPlayerUtility();

private:

    CPlayerUtility();

    void ConstructL(const TDesC& aFileName);

public:

    void Play();

    void Stop();

public: // from MMdaAudioToneObserver

          void MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration);

          void MapcPlayComplete(TInt aError);

private:

    CMdaAudioPlayerUtility* iPlayUtility;

    TBool                                           iPlaying,iPrepared;

};

 

用C++完成这道题,不改变main函数 设计一个抽象基类 MediaFile,然后派生出不同类型的媒体文件类,实现一个模拟的多媒体播放器系统。 抽象基类设计: 纯虚函数 play() - 模拟播放媒体文件 纯虚函数 getInfo() - 获取媒体文件信息 纯虚函数 getDuration() - 获取媒体时长 保护成员变量:文件名(filename)、文件大小(fileSize) 派生类实现: AudioFile:音频文件,包含比特率(bitrate)、艺术家(artist)属性 VideoFile:视频文件,包含分辨率(resolution)、帧率(framerate)属性 StreamingMedia:流媒体,包含流媒体URL(url)、缓冲时间(bufferTime)属性 播放器实现: 使用原始指针数组管理媒体文件 手动管理内存 实现基本的播放列表功能 #include <iostream> #include <cstring> using namespace std; // 抽象基类 MediaFile class MediaFile { protected: char* filename; double fileSize; // in MB public: MediaFile(const char* name, double size) : fileSize(size) { filename = new char[strlen(name) + 1]; strcpy(filename, name); } virtual ~MediaFile() { delete[] filename; } virtual void play() = 0; virtual void getInfo() = 0; virtual double getDuration() = 0; // in seconds }; // AudioFile 类定义 class AudioFile : public MediaFile { private: int bitrate; // in kbps char* artist; public: //实现构造函数 AudioFile(const char* name, double size, int br, const char* art) //实现析构函数 ~AudioFile() void play() { cout << "Playing audio file: " << filename << endl; cout << "Artist: " << artist << endl; } void getInfo() { cout << "Audio File: " << filename << " (" << fileSize << " MB), " << bitrate << " kbps, Artist: " << artist << endl; } double getDuration() { return (fileSize * 1024 * 1024 * 8) / (bitrate * 1000); } }; // VideoFile 类定义 class VideoFile : public MediaFile { private: char* resolution; double framerate; public: VideoFile(const char* name, double size, const char* res, double fps) : MediaFile(name, size), framerate(fps) { resolution = new char[strlen(res) + 1]; strcpy(resolution, res); } ~VideoFile() { delete[] resolution; } //实现play()函数 void play() //实现getInfo()函数 void getInfo() double getDuration() { // 简单假设1MB数据对应1秒视频 return fileSize; } }; // 播放器类 class MediaPlayer { private: static const int MAX_FILES = 10; MediaFile* files[MAX_FILES]; int count; public: //实现构造函数 MediaPlayer() //实现析构函数 ~MediaPlayer() bool addFile(MediaFile* file) { if (count >= MAX_FILES) { return false; } files[count++] = file; return true; } void playAll() const { for (int i = 0; i < count; i++) { files[i]->play(); cout << "Duration: " << files[i]->getDuration() << " seconds" << endl; cout << "---------------------" << endl; } } //实现listFiles() void listFiles() }; int main() { MediaPlayer player; // 添加媒体文件到播放器 player.addFile(new AudioFile("song.mp3", 5.2, 320, "Artist A")); player.addFile(new VideoFile("movie.mp4", 450.0, "1920x1080", 24.0)); // 显示播放列表 player.listFiles(); // 播放所有媒体文件 cout << "\nPlaying all media files:" << endl; player.playAll(); return 0; } 输出格式 根据测试代码中的调用,输出相应的播放信息和文件详情。要求输出为 Playlist Contents (2 files): Audio File: song.mp3 (5.2 MB), 320 kbps, Artist: Artist A Video File: movie.mp4 (450 MB), 1920x1080, 24 fps Playing all media files: Playing audio file: song.mp3 Artist: Artist A Duration: 136.315 seconds --------------------- Playing video file: movie.mp4 Resolution: 1920x1080, Framerate: 24 fps Duration: 450 seconds ---------------------
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值