Daniel's Intro to SDL2

Finally, we can add some sound effects with SDL2's built-in super basic audio functions:

static SDL_AudioSpec g_explodeAudioSpec;
static uint8* g_explodeAudioBuf = nullptr;
static uint32 g_explodeAudioLen = 0;
static SDL_AudioDeviceID g_audioDevice;

bool LoadAudio(std::string file, SDL_AudioSpec* spec, uint8* buf, uint32* len)
{
    std::string f = g_dataPath + file;
    const char* s = f.c_str();
    if (SDL_LoadWAV(s, spec, &buf, len) == nullptr)
    {
        ss.str("");
        ss << "Failed to load audio: " << f << SDL_GetError();
        LOG_FAIL(ss.str());
        return false;
    }
    ss.str("");
    ss << "Loaded audio: " << f;
    LOG_INFO(ss.str())
    
    return true;
}

bool PlayExplodeAudio()
{
    if (SDL_QueueAudio(g_audioDevice, g_explodeAudioBuf, g_explodeAudioLen) != 0)
    {
        ss.str("");
        ss << "Failed to play reveal audio: " << SDL_GetError();
        LOG_FAIL(ss.str());
        return false;
    }
    
    return true;
}

// IN THE AppInit() FUNCTION

if (!LoadAudio("explode.wav", &g_explodeAudioSpec, g_explodeAudioBuf, &g_explodeAudioLen))
    return false;

SDL_AudioSpec desiredAudio;
SDL_zero(desiredAudio);
desiredAudio.freq = 48000;
desiredAudio.format = AUDIO_F32;
desiredAudio.channels = 2;
desiredAudio.samples = 4096;
g_audioDevice = SDL_OpenAudioDevice(nullptr, 0, &desiredAudio, nullptr, SDL_AUDIO_ALLOW_ANY_CHANGE);
if (g_audioDevice == 0)
{
    ss.str("");
    ss << "Failed to open audio device: " << SDL_GetError();
    LOG_FAIL(ss.str());
    return false;
}
SDL_PauseAudioDevice(g_audioDevice, 0);
LOG_INFO("Opened audio device.");

// IN THE AppCleanup() FUNCTION

SDL_CloseAudioDevice(g_audioDevice);

if (g_explodeAudioBuf)
    SDL_FreeWAV(g_explodeAudioBuf); g_explodeAudioBuf = nullptr;

And that's it! You've got all the knowledge you need to make really interesting games with SDL2. I hope you enjoyed.

Don't forget that you can get all of my code and assets at github.com/DanielMTyler/minesweeper.