#include "sound.hpp"
Sound::Sound(void)
{
device = nullptr;
primary = nullptr;
}
Sound::~Sound(void)
{
if (playlist.size()>null)
{
for (unsigned int i = null; i < playlist.size(); i++)
{
RELEASE(playlist[i].buffer);
}
}
RELEASE(primary);
RELEASE(device);
}
void Sound::initialization(HWND hwnd)
{
DSBUFFERDESC bd;
WAVEFORMATEX wfx;
DirectSoundCreate8(nullptr, &device, nullptr);
device->SetCooperativeLevel(hwnd, DSSCL_PRIORITY);
bd.dwSize = sizeof(DSBUFFERDESC);
bd.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRLVOLUME;
bd.dwBufferBytes = null;
bd.dwReserved = null;
bd.lpwfxFormat = null;
bd.guid3DAlgorithm = GUID_NULL;
device->CreateSoundBuffer(&bd, &primary, nullptr);
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nSamplesPerSec = 44100;
wfx.wBitsPerSample = 16;
wfx.nChannels = 2;
wfx.nBlockAlign = (wfx.wBitsPerSample / 8) * wfx.nChannels;
wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
wfx.cbSize = null;
primary->SetFormat(&wfx);
}
void Sound::destroy(void)
{
delete this;
}
void Sound::add(string filename)
{
FILE * ptr_file;
uchar * buffer_data;
uchar * buffer_ptr;
ulong buffer_size;
WavFileFormat wav;
WAVEFORMATEX wfx;
DSBUFFERDESC bd;
IDirectSoundBuffer * temp = nullptr;
IDirectSoundBuffer8 * SoundBuffer = nullptr;
fopen_s(&ptr_file, filename, "rb");
fread(&wav, sizeof(wav), 1, ptr_file);
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nSamplesPerSec = 44100;
wfx.wBitsPerSample = 16;
wfx.nChannels = 2;
wfx.nBlockAlign = (wfx.wBitsPerSample / 8) * wfx.nChannels;
wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
wfx.cbSize = null;
bd.dwSize = sizeof(DSBUFFERDESC);
bd.dwFlags = DSBCAPS_CTRLVOLUME;
bd.dwBufferBytes = wav.dataSize;
bd.dwReserved = null;
bd.lpwfxFormat = &wfx;
bd.guid3DAlgorithm = GUID_NULL;
device->CreateSoundBuffer(&bd, &temp, NULL);
temp->QueryInterface(IID_IDirectSoundBuffer8, (void**)&SoundBuffer);
temp->Release();
temp = nullptr;
fseek(ptr_file, sizeof(WavFileFormat), SEEK_SET);
buffer_data = new unsigned char[wav.dataSize];
fread(buffer_data, 1, wav.dataSize, ptr_file);
fclose(ptr_file);
SoundBuffer->Lock(0, wav.dataSize, (void**)&buffer_ptr, (DWORD*)&buffer_size, nullptr, null, null);
memcpy(buffer_ptr, buffer_data, wav.dataSize);
SoundBuffer->Unlock((void*)buffer_ptr, buffer_size, nullptr, null);
BufferSound track;
track.buffer = SoundBuffer;
track.id = filename;
playlist.push_back(track);
delete[] buffer_data;
buffer_data = nullptr;
}
void Sound::release(string filename)
{
for (uint i = null; i < playlist.size(); i++)
{
if (playlist[i].id == filename)
{
RELEASE(playlist[i].buffer);
}
}
}
void Sound::play(string filename)
{
for (uint i = null; i < playlist.size(); i++)
{
if (playlist[i].id == filename)
{
playlist[i].buffer->SetCurrentPosition(null);
playlist[i].buffer->SetVolume(DSBVOLUME_MAX);
playlist[i].buffer->Play(null, null, null);
}
}
}
void Sound::stop(string filename)
{
for (uint i = null; i < playlist.size(); i++)
{
if (playlist[i].id == filename)
{
playlist[i].buffer->Stop();
}
}
}