Play music in C program

10

I need to run a song while running a program in C. In Windows we can do this - if the file is in the same program directory:

#include<stdio.h>
#include<stdlib.h>
int main (){

  system("start music.mp3");
  return 0;
}

The file will be executed. Do you know the equivalent in unix? I researched but could not pass the parameters correctly to the library functions, which possibly does this: link

    
asked by anonymous 14.12.2015 / 00:04

1 answer

8

The answer below considers the use of a command line program, as done in the question (for Windows). Another approach would be to use a C library to play MP3. Certainly there is some.

The first step is to install an MP3 player that can be triggered by the command line. There are several, one of them is mpg123.

If you are in a Debian-based distribution, you can install mpg123, like this:

sudo apt-get install mpg123 

When you do this, you call it via the command line:

mpg123 nomeDaMusica.mp3 &

O & in the line is used so that its command line does not remain locked waiting for the return of the command.

In your C code, you do this:

#include<stdio.h>
#include<stdlib.h>
int main (){

  system("mpg123 Rachmaninoff\ -\ Prelude\ in\ C-sharp\ minor.mp3 &");
  return 0;
}

Note that the name of the MP3 file is: Rachmaninoff - Prelude in C-sharp minor.mp3

However, for bash dealing with spaces it is necessary to use the \ break character.

    
14.12.2015 / 00:28