Search code examples
go2dsdl-2audio-playerweather

Cannot initialize music using SDL2_Mixer, reports unrecognized audio format


My app utilizes SDL2 to render weather data to a window, and I would like to play some music in the background indefinitely from a generated queue. I have that part done, but loading music is where the issue occurs. Every time I try to LoadMUS a song within the queue it states unrecognized audio format. This is what my code looks like.

Lines 277 - 280, when I initialize SDL for audio and video. Works fine.

if err := sdl.Init(sdl.INIT_AUDIO | sdl.INIT_VIDEO); err != nil {
    log.Fatalf("Failed to initialize SDL: %s", err)
}
defer sdl.Quit()

Lines 282 to 285, when I init the mixer. Works fine as well.

if err := mix.Init(mix.INIT_FLAC | mix.INIT_OGG); err != nil {
    log.Fatalf("Failed to initialize mixer: %s", err)
}
defer mix.Quit()

Lines 292 - 305, when I populate the music queue. Also works fine.

var music []string

err = filepath.Walk("assets/music", func(path string, info os.FileInfo, err error) error {
    if err != nil {
        return err
    }
    if !info.IsDir() && (filepath.Ext(path) == ".flac" || filepath.Ext(path) == ".ogg") {
        music = append(music, path)
    }
    return nil
})

if err != nil {
    log.Fatalf("Failed to queue music: %s", err)
    return
}

Shortly after, Lines 307 - 314, when I try to LoadMUS every file in the queue. This is where the issues arise.

for _, file := range music {
    music, err := mix.LoadMUS(file)
    if err != nil {
        log.Fatalf("Failed to load music: %s", err)
        continue
    }
    defer music.Free()
}

When I have the code above in my program, Go prints this.

2023/03/30 19:57:18 Failed to load music: Unrecognized audio format

I am trying to load FLAC files converted from FFMPEG. I've also attempted to use MP3 files and WAV files (by changing the init flags and files within assets to their working counterparts) but they don't work as well.

If it helps, the OS I am using is Windows 11, and I am using MSYS2 to for Go's SDL module to be able to utilize the SDL2 libraries. I also compile my code using the following command.

go build -ldflags="-s -w" -gcflags="-trimpath=$PWD" -race main.go

Solution

  • You need to open audio device before loading sounds. Call mix.OpenAudio or mix.OpenAudioDevice with appropriate parameters, e.g.

    mix.OpenAudio(48000, sdl.AUDIO_S16, 2, 4096);