View Full Version : Play sound on a Mac

12-27-2010, 11:57 AM
>>> Split from http://cboard.cprogramming.com/linux-programming/105923-c-program-play-sound.html - please don't dig up old posts, see the rules >>>

DWK was right about my invocation of "execvp" being wrong -- hopefully i'm about to correct myself.

If your problem with using "system" or "exec" is that you can't stop playback after it's started, then I have your solution (I once made a perl/Tk mp3 app where this figured in). Linux uses process id's ("pid"s) to track all running processes (see a list with "ps"), and you can signal the mp3 playing process to do different things with it's pid.

If you use a simple console based app like mpg123, you can call it without any pop-up windows popping up, etc -- it just plays the file. Then get the pid and kill it when you want. In perl "system" forks a process automatically and returns you the new pid (easy). In C, running a separate program with "system" and "exec" does NOT give you a new pid -- so if you kill the "mpg123" process you will kill your entire program. So you have to fork a process (=what I learned about C today).

Anyway, the following code will play a song until you hit ENTER, then it kills mpg123 (stopping the playback) and leaves a message.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // for execlp

int main () {
pid_t x; // a special kind of int
char kil[20] = "kill -s 9 ";

x = fork(); /* now there's actually two "x"s:
if fork succeeds, "x" to the CHILD PROCESS is the return value of fork (0)
and "x" to the PARENT PROCESS is the actual system pid of the child process.*/

if (x < 0) { // just in case fork fails
puts("fork failure");
else if (x == 0) { // therefore this block will be the child process
execlp("mpg123", "mpg123", "-q", "/songs/bertha.mp3", 0);
} // see GNU docs, "system" also works
else { printf("from parent: mpg123 is pid %d\nENTER to quit\n", x);
getchar(); // wait for user input
printf("All ");
} /* witness that the "else if" and "else" blocks are both executed here in parallel. The "else"
(parent) block is continuous with the rest of the program (since the PARENT PROCESS is actually
the program itself) so... */

Get it? Anyway, that might be all you need.


I wanna use the above code to play *.mp3. I replaced the filename "/songs/bertha.mp3" by a filename i want to play on. i complied and run it with the following command

gcc *.c


i am getting the following

from parent: mpg123 is pid 9832
ENTER to quit

It doesn't play the mp3. It seams that i missed something. Can you help me?



P.S : I am working on mac.

12-27-2010, 04:41 PM
Do you have a program called "mpg123" on your Mac? I don't.

12-27-2010, 05:18 PM
Nor do I.

12-27-2010, 05:31 PM
I don't have it.

12-27-2010, 05:41 PM
Soooooooooo, change the name "mpg123" to whatever you have on your system that plays mp3 files. (Or I suppose you can go get mpg123.)