Dave's Brain

Browse - Programming Tips - How do I play audio/sounds on the command line with Linux?

Date: 2011feb2
OS: Linux

Q.  How do I play audio/sounds on the command line with Linux?

A.  If its a .mp3 you can use /usr/bin/mpg123.
If its a .au or .wav you can use /usr/bin/play.

For Red Hat / Fedora mpg123 is in the mpg123 package.
/usr/bin/play is in the sox package. ie

dnf install mpg123 sox
will install them. Here's a small perl command line script which checks the extension on an audio file and uses appropriate program to play it.
#!/usr/bin/perl use strict; sub isMp3($) { my($file) = @_; return $file =~ m/.mp3$/i; } sub play($) { my($file) = @_; my(@args); if (isMp3($file)) { if (!defined $ENV{'HOME'}) { $ENV{'HOME'} = '/tmp'; # mpg123 needs a home directory } @args = ("/usr/bin/mpg123", $file); } else { @args = ("/usr/bin/play", $file); } return system @args == 0; } sub main() { if (scalar @ARGV != 1) { printf STDERR "Exactly one audio file required\n"; exit(1); } play($ARGV[0]); } main();

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.