WaveOut.cpp
上传用户:amei960
上传日期:2007-02-05
资源大小:143k
文件大小:3k
- #include "stdafx.h"
- #include "WaveOut.h"
- #pragma comment(lib,"Winmm")
- CWaveOut::CWaveOut()
- {
- memset(&waveCaps,0,sizeof(waveCaps));
- bDevOpen = FALSE;
- m_hWave = 0;
- //----------
- nChannels = 1;
- dwHertZ = HERTZ_POOR;
- wBits = 16;
- //----------
- m_BufferQueue = 0;
- }
- CWaveOut::~CWaveOut()
- {
- Stop();
- }
- BOOL CWaveOut::IsExistDevice()
- {
- if( waveOutGetNumDevs() <= 0 )
- {
- return FALSE;
- }
- return TRUE;
- }
- WAVEOUTCAPS* CWaveOut::GetDeviceCap()
- {
- MMRESULT mRet = waveOutGetDevCaps(WAVE_MAPPER,&waveCaps,sizeof(waveCaps));
- if( mRet == MMSYSERR_NOERROR )
- return &waveCaps;
- return NULL;
- }
- BOOL CWaveOut::Open()
- {
- if( bDevOpen )
- {
- return FALSE;
- }
- MMRESULT mRet;
- WAVEFORMATEX wfx;
- wfx.wFormatTag = WAVE_FORMAT_PCM;
- wfx.nChannels = nChannels;
- wfx.nSamplesPerSec = dwHertZ;
- wfx.nAvgBytesPerSec = nChannels * dwHertZ * wBits / 8;
- wfx.nBlockAlign = wBits * nChannels / 8;
- wfx.wBitsPerSample = wBits;
- wfx.cbSize = 0;
- mRet = waveOutOpen(0,WAVE_MAPPER,&wfx,0,0,WAVE_FORMAT_QUERY);
- if( mRet != MMSYSERR_NOERROR )
- {
- return FALSE;
- }
- mRet = waveOutOpen(&m_hWave,WAVE_MAPPER,&wfx,(DWORD)waveOutProc,(DWORD)this,CALLBACK_FUNCTION);
- if( mRet != MMSYSERR_NOERROR )
- {
- return FALSE;
- }
- bDevOpen = TRUE;
- return TRUE;
- }
- void CWaveOut::Close()
- {
- if (!bDevOpen)
- {
- return;
- }
- if(!m_hWave)
- {
- return;
- }
- waveOutReset(m_hWave);
- MMRESULT mRet = waveOutClose(m_hWave);
- if( mRet != MMSYSERR_NOERROR )
- {
- return;
- }
- m_hWave = 0;
- bDevOpen = FALSE;
- }
- void CALLBACK CWaveOut::waveOutProc(HWAVEOUT hwo,UINT uMsg,DWORD dwInstance,DWORD dwParam1,DWORD dwParam2)
- {
- CWaveOut *pWaveOut;
- pWaveOut = (CWaveOut *)dwInstance;
- WAVEHDR* pWaveHead = NULL;
- switch(uMsg)
- {
- case WOM_OPEN:
- break;
- case WOM_CLOSE:
- break;
- case WOM_DONE:
- pWaveHead = (WAVEHDR*)dwParam1;
- if( pWaveHead != NULL )
- {
- waveOutUnprepareHeader(hwo,pWaveHead,sizeof(WAVEHDR));
- pWaveOut->SubBuffer();
- delete []pWaveHead->lpData;
- delete pWaveHead;
- }
- break;
- }
- }
- BOOL CWaveOut::Start()
- {
- if( !Open() )
- {
- return FALSE;
- }
- return TRUE;
- }
- BOOL CWaveOut::Play(char* buf,UINT nSize)
- {
- if( !bDevOpen )
- {
- return FALSE;
- }
- if( GetBufferNum() >= 5 )
- {
- return FALSE;
- }
- MMRESULT mRet;
- char* lpData = NULL;
- WAVEHDR* pWaveHead = new WAVEHDR;
- ZeroMemory(pWaveHead,sizeof(WAVEHDR));
- lpData = new char[nSize];
- pWaveHead->dwBufferLength = nSize;
- memcpy(lpData,buf,nSize);
- pWaveHead->lpData = lpData;
- mRet = waveOutPrepareHeader(m_hWave,pWaveHead,sizeof(WAVEHDR));
- if( mRet != MMSYSERR_NOERROR )
- {
- return FALSE;
- }
- mRet = waveOutWrite(m_hWave,pWaveHead,sizeof(WAVEHDR));
- if( mRet != MMSYSERR_NOERROR )
- {
- return FALSE;
- }
- AddBuffer();
- return TRUE;
- }
- void CWaveOut::Stop()
- {
- Close();
- }