Search code examples
c++audiosdlmp3

ncurses + SLD2 and SDL2_Mixer: No sound when trying to play mp3


I am writing a program in C++ that uses the ncurses library and also plays sound effects. While the build compiles, there is no sound.

I have installed and added both the SDL2 and SDL2_Mixer frameworks to my IDE project (I'm using Xcode). I have also added the mp3 file to the same directory as my other project files. Here's my code:

#include <SDL2/SDL.h>
#include <SDL2_Mixer/SDL_Mixer.h>
#if defined(WIN32)
#include "curses.h"
#else
#include <curses.h>
#endif
...
int main(int argc, char * argv[]) {
Mix_Music *music;

// Initialize music.
if (SDL_Init(SDL_INIT_AUDIO) < 0) {
    fprintf(stderr, "unable to initialize SDL\n");
    exit(EXIT_FAILURE);
}
if (Mix_Init(MIX_INIT_MP3) != MIX_INIT_MP3) {
    fprintf(stderr, "unable to initialize SDL_mixer\n");
    exit(EXIT_FAILURE);
}
if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 1024) != 0) {
    fprintf(stderr, "unable to initialize audio\n");
    exit(EXIT_FAILURE);
}
Mix_AllocateChannels(1); // only need background music
music = Mix_LoadMUS("sound.mp3");
if (music) {
    Mix_PlayMusic(music, -1);
}
...
Mix_HaltMusic();
Mix_FreeMusic(music);
Mix_CloseAudio();
Mix_Quit();


return 0;
}

The build compiles successfully, I go to the terminal and open my project, and then... no sound!? What am I doing wrong?


Solution

  • It turned out that what was needed was an absolute path to the music file:

    Mix_AllocateChannels(1); 
    music = Mix_LoadMUS("/.../sound.mp3");
    if (music) {
    Mix_PlayMusic(music, -1);
    }