ICT290 / src / ShaysWorld / Sound.cpp
Sound.cpp
Raw
// Sound.cpp: implementation of the CSound class.
//
//////////////////////////////////////////////////////////////////////

#include <malloc.h>
#include <memory.h>

#include "EasySound.h"
#include "Sound.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CSound::CSound(const string& filename, int iSoundID) {
    m_iSoundID = iSoundID;
    Uint32 len;
    if (SDL_LoadWAV(filename.c_str(), &m_spec, &m_data, &len) == NULL) {
        fprintf(stderr,
                "Couldn't load %s: %s\n",
                filename.c_str(),
                SDL_GetError());
        m_len = CSoundTime(0);
        return;
    }
    m_len = CSoundTime(len);
    m_pos = CSoundTime(0);

    CEasySound* es = CEasySound::Instance();
    SDL_AudioSpec obtained = es->GetObtained();
    SDL_AudioCVT cvt;

    SDL_BuildAudioCVT(&cvt,
                      m_spec.format,
                      m_spec.channels,
                      m_spec.freq,
                      obtained.format,
                      obtained.channels,
                      obtained.freq);
    cvt.buf = (Uint8*)malloc(m_len.GetSDLTime() * cvt.len_mult);
    memcpy(cvt.buf, m_data, m_len.GetSDLTime());
    cvt.len = m_len.GetSDLTime();
    SDL_ConvertAudio(&cvt);
    SDL_FreeWAV(m_data);

    SDL_LockAudio();
    m_data = cvt.buf;
    // the new length of sound after convert from 8bit to 16bit
    m_len = CSoundTime(cvt.len_cvt);
    m_pos = CSoundTime(0);
    SDL_UnlockAudio();
}

CSound::~CSound() {
    SDL_FreeWAV(m_data);
}

CSoundTime CSound::GetLength() {
    return CSoundTime(m_len);
}