Perform music in the program in C

Asked

Viewed 3,215 times

10

I need to run a song while running a program in C. In Windows we can do so - 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 run. do you know what the Unix equivalent is? I searched but could not pass the parameters correctly to the library functions, which possibly does this: https://www.cs.cf.ac.uk/Dave/C/node22.html

1 answer

9

The answer below considers using a program via the command line, as asked in the question (for Windows). Another approach would be to use a C library to play the MP3. Surely 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, thus:

sudo apt-get install mpg123 

That done, you call him via command line:

mpg123 nomeDaMusica.mp3 &

& On the line is for your command line not to be locked and waiting for command to return.

In your code C, you do so:

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

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

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

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

  • other interesting player: system("firefox rac.mp3") system(""qvlc -q --play-and-Exit 8.mp3 &")`; +1 by choice of the Preludium C#m!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.