PeterX {l Wrote}:How do I play a sound(file) from a C console program on Linux?
Back in the old days when people were stupid and dumb so couldn't understand how magnificent pulseaudio is, there was a /dev/dsp device file. You could just write the raw data into that file. Like this:
- {l Code}: {l Select All Code}
cat sound.wav > /dev/dsp
If your distro ships a kernel that provides the dsp device file, you can still do this.
Sadly these days /dev/dsp is missing, and you must use a library which hides OSS / ALSA / whatever kernel interface details, libao is good. I'd also point out that SDL can handle audio natively just fine with the low-level
SDL_OpenAudioDevice interface. The reason why people don't use this directly is because it can only play one audio stream (which is exactly what you want).
For playing multiple sounds at once, one have to mix those streams into a single stream first. Basically that's all what SDL_mixer does, but that library's source is relatively complicated and complex. Here's a
simple mixer library that does that too, but it is useful to learn how to use SDL's low-level audio interface (NOTE: since this is the simplest possible mixer with the simplest code base, its features are very limited, but, single C file, easy to learn from it, and you'll only need one sound anyway).
PeterX {l Wrote}:I have a simple textonly program that should play a sound file. (No synchronizing, no music, no reacting to game status.)
That would be as simple as
- {l Code}: {l Select All Code}
playSound("sound.wav", SDL_MIX_MAXVOLUME);
Without a mixer library, using only SDL's low-level interface, see
this gist. It plays an ogg file (with stb_vorbis), but you could fill up the audiodata[] buffer using the native SDL_LoadWav() function too if you only need .wav sounds.
PeterX {l Wrote}:And if I use SDL, I can't use printf() anymore?
Nope, you can. Here's an
example console app that plays some music and sounds from command line, it has no issues with printf at all. Try it out, add some printf in that code. The gist link above also contains some printf calls.
Cheers,
bzt