0

I am using libSDL2's mixer for playing audio stored as wav files in a project of mine, but I need to do some signal processing on the audio data and that requires me to access the individual samples (i.e: as an array of doubles).

So I'm looking for a way to either retrieve the samples from a MixChunk, or to feed an array of doubles to libSDL for playback.

Here is an example of my code for playing the wav files:

#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <iostream>

int playSound(char path[], int channel) {
  if (SDL_Init(SDL_INIT_AUDIO) < 0)
    return -1;

  // Initialize SDL_mixer
  if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1)
    return -1;

  Mix_Chunk *wave = NULL;
  wave = Mix_LoadWAV(path);

  if (wave == NULL) {
    std::cout << "Error: Could not load .wav file: " << path << std::endl;
    return -1;
  }

  if (Mix_PlayChannel(channel, wave, 0) == -1) {
    std::cout << "Error: Could not play wav file (" << path << ") on channel "
              << channel << std::endl;
    return -1;
  }

  while (Mix_Playing(channel)) {
    printf("%i\n", wave->abuf);
  }
  Mix_FreeChunk(wave);
}


void initializeAudioDevice() {
  if (SDL_Init(SDL_INIT_AUDIO) < 0)
    printf("Error: Can't open audio device!\n");
  if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 256) == -1)
    printf("Error: Failed to setup audio device!\n");
}

int main() {
  initializeAudioDevice();
  char path[] = "sound.wav";
  playSound(path, 1);
  return 0;
}

As you can see I tried to print out the content of the MixChunk->abuf property but that doesn't give me the samples.

Thank you for helping to get me on the right track.

Louis T
  • 75
  • 8
  • 1
    You just want to feed your custom data to sound card? Then you don't need `SDL_mixer` at all (its primary task is mixing multiple sounds into one). Take a look at https://wiki.libsdl.org/SDL_OpenAudioDevice , https://wiki.libsdl.org/SDL_AudioSpec and http://hg.libsdl.org/SDL/file/872d4ecd39f6/test/loopwave.c - set up callback and feed your data into given buffer. – keltar Dec 06 '19 at 08:31
  • Interesting, thanks a lot. However I do need SDL_mixer for the logic of having several channels where sounds can play and where two sounds playing on the same channel cut each other off. I'll see if I can implement that logic on my own. – Louis T Dec 07 '19 at 10:56

0 Answers0