#include "StdAfx.h"
#include "SoundBuffer.h"


cSoundBuffer::cSoundBuffer(const char* fileName)
: m_data(NULL)
, m_dpos(NULL)
, m_dlen(NULL)
{
	SDL_AudioSpec wave;
	Uint8 *data;
	Uint32 dlen;
	SDL_AudioCVT cvt;

	//Load the sound file and convert it to 16-bit stereo at 22kHz
	if ( SDL_LoadWAV(fileName, &wave, &data, &dlen) == NULL )
	{
		assert(false && "you might have a pathing issue.  Did you set your 'Working Directory' to '$(OutDir)' in your GameEXE vcproj properties?");
		fprintf(stderr, "Couldn't load %s: %s\n", fileName, SDL_GetError());
		return;
	}
	SDL_BuildAudioCVT(&cvt, wave.format, wave.channels, wave.freq, AUDIO_S16, 2, 22050);
	cvt.buf = (unsigned char*)malloc(dlen*cvt.len_mult);
	memcpy(cvt.buf, data, dlen);
	cvt.len = dlen;
	SDL_ConvertAudio(&cvt);
	SDL_FreeWAV(data);

	SDL_LockAudio();
	m_data = cvt.buf;
	m_dlen = m_dpos = cvt.len_cvt; //start the sound at the very end so it will be considered "finished"
	SDL_UnlockAudio();
}


void cSoundBuffer::Play()
{
	m_dpos = 0;
}


void cSoundBuffer::MixAudio(Uint8 *stream, int len)
{
	int amount = m_dlen - m_dpos;
	if ( amount > len )
	{
		amount = len;
	}
	SDL_MixAudio(stream, &m_data[m_dpos], amount, SDL_MIX_MAXVOLUME);
	m_dpos += amount;
}
