#include "stdafx.h"
#include "FlashSoundRecorder.h"

CFlashSoundRecorder::CFlashSoundRecorder() : 
	m_hmmio(NULL), 
	m_bFirstTime(TRUE), 
	m_hFPC(NULL)
{
}

CFlashSoundRecorder::~CFlashSoundRecorder()
{
}

void CFlashSoundRecorder::Start(LPCTSTR szWAVPath, HFPC hFPC)
{
	m_strWAVPath = szWAVPath;
	m_hFPC = hFPC;

	FPC_SetSoundListener(m_hFPC, &StaticSoundListener, (LPARAM)this);
}

void CFlashSoundRecorder::Stop()
{
	if (NULL != m_hFPC)
	{
		FPC_SetSoundListener(m_hFPC, NULL, 0);
		m_hFPC = NULL;
	}

	VERIFY(MMSYSERR_NOERROR == mmioAscend(m_hmmio, &m_data, 0));

	VERIFY(MMSYSERR_NOERROR == mmioAscend(m_hmmio, &m_wave, 0));

	VERIFY(MMSYSERR_NOERROR == mmioClose(m_hmmio, 0));
	m_hmmio = NULL;

	m_bFirstTime = TRUE;
}

void CFlashSoundRecorder::SoundListener(PWAVEFORMATEX pWaveFormat, LPWAVEHDR pWaveHeader, UINT nHeaderSize)
{
	if (m_bFirstTime)
	{
		m_bFirstTime = FALSE;

		m_hmmio = mmioOpen(m_strWAVPath.GetBuffer(m_strWAVPath.GetLength() + 1), NULL, MMIO_ALLOCBUF | MMIO_CREATE | MMIO_WRITE);
		m_strWAVPath.ReleaseBuffer();

		ZeroMemory(&m_wave, sizeof(m_wave));
		m_wave.fccType = mmioFOURCC('W','A','V','E');
		VERIFY(MMSYSERR_NOERROR == mmioCreateChunk(m_hmmio, &m_wave, MMIO_CREATERIFF));

		MMCKINFO fmt = { 0 };
		fmt.ckid = mmioFOURCC('f','m','t',' ');
		fmt.cksize = sizeof(WAVEFORMATEX) + pWaveFormat->cbSize;
		VERIFY(MMSYSERR_NOERROR == mmioCreateChunk(m_hmmio, &fmt, 0));
		VERIFY(fmt.cksize == mmioWrite(m_hmmio, (LPCSTR)pWaveFormat, fmt.cksize));

		VERIFY(MMSYSERR_NOERROR == mmioAscend(m_hmmio, &fmt, 0));

		ZeroMemory(&m_data, sizeof(m_data));
		m_data.ckid = mmioFOURCC('d','a','t','a');
		VERIFY(MMSYSERR_NOERROR == mmioCreateChunk(m_hmmio, &m_data, 0));
	}

	VERIFY(pWaveHeader->dwBufferLength == mmioWrite(m_hmmio, pWaveHeader->lpData, pWaveHeader->dwBufferLength));
}
