How to find the duration or length of an MP3 File in C++

In this tutorial, we are going to learn how to find the duration or length of an MP3 File in C++.  We will use the mciSendString() function which exists in “Windows.h” header. This function helps us do many operations on an audio file. Let’s understand it.

Find the duration or length of an MP3 File in C++

To find the duration of an MP3 file we will follow the following steps:

  • Save the mp3 file in the same folder where your program is saved.
  • Now, open Dev C++ application.
  • Create a new project and change the file extension to .cpp and save.
  • Go to Project and select project options.
  • Go to the Parameters tab and type “-lwinmm” under the linker section and click ok.
  • Now, run the below code on your system.

Here is the program to implement the above. The file used here is “Music.mp3”. To open your file in the program insert your file name in the first call of mciSendString() where we have used command string “open \”Music.mp3\” type mpegvideo alias mp3″. Replace Music.mp3 with your mp3 file name.

#include<iostream>
#include<ctime>
#include<windows.h>

#pragma comment(lib, "Winmm.lib")
 
using namespace std;
 
int main()
{
  cout<<"Press any key to play the file\n";
  cout<<"You pressed "<<char(cin.get())<<" and the audio is playing...\n";
  
   //opening the mp3 file
   mciSendString("open \"Music.mp3\" type mpegvideo alias mp3", NULL, 0, NULL);
    
    //start time
    time_t start=time(0);
    //play the mp3 file
    mciSendString("play mp3 wait", NULL,  0, NULL);
    
    //end time
    time_t end=time(0);
   
    //total duration
    int length=end-start;
    cout<<length<<" seconds"<<endl;
    cout<<length/60<<":"<<length%60<<endl;
   
 	//close the mp3 file
    mciSendString("close mp3", NULL, 0, NULL);
 	return 0;
 }

 

Output:

The above program will play the mp3 file and print the duration of the file in seconds on the console as shown here. The output may suffer a slight inaccuracy depending on your system.

Press any key to play the file
f
You pressed f and the audio is playing...
275 seconds
4:35

Explanation: In the above program, we have used a function mciSendString(). In the first call to this function, we have passed a command string that opens the mp3 file. In the second call to this function, we play the file and store the time in seconds just before the mp3 file begins to play and just after it finishes. That is the total duration in seconds. We can convert it into minutes and then print.

The syntax of mciSendString() function is as follows:

MCIERROR mciSendString(  LPCTSTR lpszCommand,  LPTSTR  lpszReturnString,  UINT    cchReturn,  HANDLE  hwndCallback );

To know more: Read this

Note: This program will work for .wav file as well.

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *