Zum Inhalt springen

SDL: Audio

Aus Wikibooks

Abspielen einer WAV-Datei

[Bearbeiten]
#include <SDL2/SDL.h>
#include <stdlib.h> 
 
SDL_Surface *screen;
SDL_AudioSpec spec;
Uint32 sound_len;
Uint8 *sound_buffer;
int sound_pos = 0;
 
void init_sdl (void)
{
   if (SDL_Init (SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0)
     exit (-1);
   atexit (SDL_Quit);
   screen = SDL_SetVideoMode (640, 480, 16, SDL_HWSURFACE);
   if (screen == NULL)
     exit (-1);
}
 
void Callback (void *userdata, Uint8 *stream, int len)
{
  Uint8 *waveptr;
  if (sound_pos + len > sound_len)
  {
    return;
  }
  waveptr = sound_buffer + sound_pos;
  SDL_MixAudio(stream, waveptr, len, SDL_MIX_MAXVOLUME);
  sound_pos += len;
}
 
void play (void)
{
   if (SDL_LoadWAV ("torvalds-says-linux.wav", &spec, &sound_buffer, &sound_len) == NULL)
     exit (-1);
   spec.callback = Callback;
   if (SDL_OpenAudio (&spec, NULL) < 0)
     {
       printf ("Kann audio nicht öffnen: %s\n", SDL_GetError ());
       exit (-1);
     }
   SDL_PauseAudio (0);
}
 
int main (void)
{
   init_sdl ();
   play ();
   SDL_Delay (1000);
   /* Speicher nur freigeben, wenn WAV nicht mehr spielt. */
   // SDL_FreeWAV (sound_buffer);
   return 0;
}