Playing a sound file
by havoc
Is there really no Linux API to just play a file?
Something like:
id = cache_file("foo.ogg"); // cache the sample play(id); // play to default device
libcanberra seems to only support playing stuff from a sound theme, not a file. PulseAudio seems to require setting up a main loop thing, creating a context, converting the file to a stream object in the right format, uploading the sample, and then finally playing it.
This should be a two-liner (with caching) and a one-liner without!
Which API should I know about?
(Is there at least an example of doing it with PulseAudio that can be quickly copied?)
My Twitter account is @havocp.
Interested in becoming a better software developer? Sign up for my email list and I'll let you know when I write something new.
Hi Havoc! Long time no see!
Phonon::MediaObject *music = Phonon::createPlayer(Phonon::MusicCategory, Phonon::MediaSource(“/path/mysong.wav”));
music->play();
should do it, on PulseAudio, GStreamer, Xine, or VLC, or on Windows or Mac.
http://doc.qt.nokia.com/4.7/phonon-overview.html#playback
HTH
import gst
player = gst.parse_launch(“playbin uri=file:///foo.ogg”)
player.set_state(gst.STATE_PLAYING)
I wouldn’t actually expect Linux itself to have a music-playing API… That would be creeping featuritis of worst sort! But there are plenty of options. Given that you’re looking at libcanberra, I’d say gstreamer? That’s 10-ish lines (http://www.gstreamer.net/data/doc/gstreamer/head/manual/html/chapter-helloworld.html if you got rid of all the error checking and bits you don’t care about).
Alternatively, in SDL it’s about 8 lines (http://gpwiki.org/index.php/C:Using_SDL_mixer_to_play_an_Ogg_music_file)
How about using GStreamer? A bit more lines, but not that many – http://gstreamer.freedesktop.org/data/doc/gstreamer/head/manual/html/chapter-components.html#section-components-playbin (the example can be shortened)
Look at gnome-games/libgames-support/games-sound.c. It’s only two lines but it can depend on how you want to have the sound triggered.
Jason, nice! it looks like libcanberra can play a filename after all.
system(“/usr/bin/paplay /usr/share/sounds/myfile.wav”) can fill some basic needs. It does when you program in shell or in Perl.
libcanberra can do that for you just fine, just set the CA_PROP_MEDIA_FILENAME property when calling ca_context_play().
ca_context_play(ca_gtk_context_get(), 0, CA_PROP_MEDIA_FILENAME, path, NULL);
If you need this from a shell use canberra-gtk-play which basically does this but a lot fancier.
Note that while just passing the one filename is sufficient we encourage you to pass more properties, to easy a11y, yadda yadda.
Thanks Lennart. This is how I ended up doing it.
what about system(“cp my.wav /dev/dsp”) ? – that might work for some files;)