#include "StdAfx.h"
#include "AudioManager.h"
#include "soundBuffer.h"


cAudioManager::cAudioManager()
: m_pTheOneSound(NULL)
{
	/* Set 16-bit stereo audio at 22Khz */
	m_fmt.freq = 22050;
	m_fmt.format = AUDIO_S16;
	m_fmt.channels = 2;
	m_fmt.samples = 512;        /* A good value for games */
	m_fmt.callback = MixAudioCallback;
	m_fmt.userdata = this; //this value gets passed into the MixAudioCallback function

	/* Open the audio device and start playing sound! */
	if ( SDL_OpenAudio(&m_fmt, NULL) < 0 )
	{
		fprintf(stderr, "Unable to open audio: %s\n", SDL_GetError());
	}

	SDL_PauseAudio(0);
}


cAudioManager::~cAudioManager()
{
	SDL_CloseAudio();

	if( NULL!=m_pTheOneSound )
	{
		delete m_pTheOneSound;
	}
}



void cAudioManager::MixAudioCallback(void *userdata, Uint8 *stream, int len)
{
	//Only play if we have data left
	if( 0==len )
	{
		return;
	}

	cAudioManager* pAudioManager = static_cast<cAudioManager*>(userdata);
	if( NULL!=pAudioManager->m_pTheOneSound )
	{
		pAudioManager->m_pTheOneSound->MixAudio(stream, len);
	}
}


cSoundBuffer* cAudioManager::CreateSoundBuffer(char *filename)
{
	//If you hit this assert, then the time has come for you to grow this class
	//and make it hold a container of sounds instead of a single sound
	assert(NULL==m_pTheOneSound && "The 'cAudioManager' is currently not equipped to be able to create more than one sound");

	m_pTheOneSound = new cSoundBuffer(filename);
	return m_pTheOneSound;
}
