• Advertisement


This topic is now archived and is closed to further replies.

Any good SDL_Audio tutorials out there?

This topic is 5001 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Guest Anonymous Poster
I suggest you use SDL_Mixer for your audio. It will mix your sounds automatically etc.


Share this post

Link to post
Share on other sites
Guest Anonymous Poster
Here is a simple one that should work:

* Sample of SDL_Audio. Compile and link with an SDL_main.
* Author: Pierre G. Richard
* Written: 4/12/2004

#include <memory.h>
#include "SDL.h"

typedef struct {
Uint8 *buffer;
Uint8 *bufMax;
Uint8 *bufCurr;
SDL_sem * playEnded;
int isEnabled;

| "Play" callback |
static void callback(void * udata, Uint8 * stream, int len)
CallbackData d = *(CallbackData *)udata;
if (d.isEnabled) {
if (d.bufCurr < d.bufMax) {
if (d.bufCurr+len > d.bufMax) {
len = d.bufMax - d.bufCurr;
((CallbackData *)udata)->bufCurr += len;
SDL_MixAudio(stream, d.bufCurr, len, SDL_MIX_MAXVOLUME);
}else {
d.isEnabled = 0; /* disable self */

| |
int main(int argc, char ** argv)
SDL_AudioSpec wave;
CallbackData d;
int bufSize;

if (argc != 2) {
fprintf(stderr, "Usage: playSound <soundFilePath>\n";
}else if (!SDL_LoadWAV(argv[1], &wave, &d.buffer, &bufSize)) {
fprintf(stderr, "Error %d loading the sound file.\n", SDL_GetError());
}else {
SDL_AudioSpec device;

device.freq = 22050; // Samples per sec (FM Radio quality)
device.format = AUDIO_S16; // Signed 16-bit little-endian samples
device.channels = 2; // Number of sound channels (stereo)
device.samples = 4096; // Size of the Audio buffer in samples
device.callback = callback; // "Play" callback
device.userdata = &d; // callback data

d.isEnabled = 0; // disable our callback
if (SDL_OpenAudio(&device, 0) < 0) {
fprintf(stderr, "Error %d opening the audio.\n", SDL_GetError());
}else {
d.playEnded = SDL_CreateSemaphore(0);
d.bufCurr = d.buffer;
d.bufMax = d.buffer + bufSize;
d.isEnabled = 1;
SDL_PauseAudio(0); // make sure we play
SDL_SemWait(d.playEnded); // wait here until the callback finishes
return 0;


Share this post

Link to post
Share on other sites
Thanks, AP. However this post was something like 3 months ago I''ve already used SDL_Mixer and generated my own Audio Manager class that allows precaching of sound files and decides which sounds to keep preloaded based on usage, etc.

Anyone interested in some further discussion on heuristics for a future Audio Manager can read this thread.


[ CodeDread ]

Share this post

Link to post
Share on other sites

  • Advertisement