1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
#include <iostream> #include <SDL2/SDL.h> // Audio callback function to handle audio playback void audioCallback(void* userdata, Uint8* stream, int len) { SDL_memset(stream, 0, len); // Clear the audio buffer // Cast userdata to SDL_AudioSpec pointer SDL_AudioSpec* spec = (SDL_AudioSpec*)userdata; // Check if audio data is available if (spec->userdata) { Uint8* audioData = (Uint8*)spec->userdata; SDL_memcpy(stream, audioData, len); // Copy audio data to the stream spec->userdata = NULL; // Clear the userdata to stop playback } } int main(int argc, char* argv[]) { if (SDL_Init(SDL_INIT_AUDIO) < 0) { // Initialize SDL audio subsystem std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl; return 1; } // Load WAV file SDL_AudioSpec wavSpec; Uint8* wavStart; Uint32 wavLength; if (SDL_LoadWAV("example.wav", &wavSpec, &wavStart, &wavLength) == NULL) { std::cerr << "Failed to load WAV file! SDL_Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } // Set up audio specifications and callback wavSpec.callback = audioCallback; wavSpec.userdata = wavStart; // Set userdata to the loaded WAV data // Open audio device if (SDL_OpenAudio(&wavSpec, NULL) < 0) { std::cerr << "Failed to open audio device! SDL_Error: " << SDL_GetError() << std::endl; SDL_FreeWAV(wavStart); SDL_Quit(); return 1; } SDL_PauseAudio(0); // Start audio playback // Wait for audio to finish playing SDL_Delay(3000); // Wait for 3 seconds (adjust as needed for your audio length) SDL_CloseAudio(); // Close audio device SDL_FreeWAV(wavStart); // Free the loaded WAV data SDL_Quit(); // Clean up SDL return 0; } |
Explanation
- Include Libraries:
#include <iostream>
: For input and output operations.#include <SDL2/SDL.h>
: For SDL functions and types.
- Audio Callback Function (
audioCallback
):- This function is called by SDL when audio needs to be played.
- It clears the audio buffer with
SDL_memset
. - Copies audio data from
userdata
to the stream buffer. - Sets
userdata
toNULL
after copying to stop playback.
- Main Function (
main
):- Initializes SDL with
SDL_Init(SDL_INIT_AUDIO)
. - Loads the WAV file using
SDL_LoadWAV
. - Checks if loading the WAV file was successful.
- Sets up the audio specifications and callback function.
- Opens the audio device with
SDL_OpenAudio
. - Starts audio playback with
SDL_PauseAudio(0)
. - Waits for a specified duration using
SDL_Delay
to allow audio to play. - Closes the audio device with
SDL_CloseAudio
. - Frees the loaded WAV data and cleans up SDL with
SDL_Quit
.
- Initializes SDL with
- Error Handling:
- The program checks for errors at each step (initialization, loading WAV, opening audio device) and outputs relevant error messages if something goes wrong.