How to Convert MP4 to MP3 in Java
Learn to convert video files to different audio file formats using four Video and Audio APIs. Read the tutorial!
Join the DZone community and get the full member experience.
Join For FreeExtracting audio data from video content can be an arduous process, particularly when attempted by hand. If you need to perform the task with large stacks of data, it can become seemingly impossible or at least prove to be a major time vacuum. Therefore, finding an appropriate API to handle the job for you means that you will be able to efficiently produce high-quality work without losing labor hours or team members to a fairly menial task.
In this tutorial, I will show you how to convert video files to different audio file formats using four Video and Audio APIs. These include MP3, M4A, WAV, and AAC. Because we have quite a few functions to the walkthrough, we will just jump in now.
For all these APIs, we will need to install our library with Maven or Gradle. To install with Maven, you’ll need to add a Jitpack reference to the repository in pom.xml, as shown below:
xxxxxxxxxx
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Then, you’ll need to add a reference to the dependency:
xxxxxxxxxx
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.54</version>
</dependency>
</dependencies>
For Gradle, add the following snippet in your root build.gradle at the end of repositories:
xxxxxxxxxx
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Then, add the dependency in build.gradle:
xxxxxxxxxx
dependencies {
implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
}
Now that we’ve completed our install, we can start running the functions. Our first function will automatically detect video and audio file formats and convert them to MP3. Some of the input formats it supports are MP4, MOV, WEBM, AAC, FLAC, M4A, MP2, MP3, OGG, WMA, and WAV. Because input files for this kind of function are often large, one API call will be made per 10 MB of file size as well as for each additional minute of processing time over five minutes, up to a maximum of 25 minutes. The maximum output file size for the function is 50 GB.
To start the process, we first need to add our imports to the top of our file. Once we’ve completed this, we can call our function:
xxxxxxxxxx
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.AudioApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
AudioApi apiInstance = new AudioApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
String fileUrl = "fileUrl_example"; // String | Optional; URL of an audio file being used for conversion. Use this option for files larger than 2GB.
Integer bitRate = 56; // Integer | Optional; Specify the desired bitrate of the converted audio file in kilobytes per second (kB/s). Value may be between 48 and 1,411. By default, the optimal bitrate will be chosen automatically.
try {
byte[] result = apiInstance.audioConvertToMp3(inputFile, fileUrl, bitRate);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AudioApi#audioConvertToMp3");
e.printStackTrace();
}
As input for this function, you will need to add your file or, optionally, a file URL. A file URL should be used for files larger than 2GB. You may also add the desired bitrate of the converted audio in kilobytes per second. This value may be between 48 and 1,411 kB/s. If no otherwise specified, the optimal bitrate will be chosen automatically. To ensure that this API works properly, you need to ensure certain requirements are met:
- Your input file or URL is valid and not encrypted or password protected
- You have input your API Key. This can be retrieved at no cost on the Cloudmersive website, providing 800 monthly calls across our API library.
The following two functions, conversions to M4A and AAC, have the same install, import, and input steps as our first example. As above, once you’ve completed the install, you can call the function.
This first block is for converting files to M4A:
xxxxxxxxxx
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.AudioApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
AudioApi apiInstance = new AudioApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
String fileUrl = "fileUrl_example"; // String | Optional; URL of an audio file being used for conversion. Use this option for files larger than 2GB.
Integer bitRate = 56; // Integer | Optional; Specify the desired bitrate of the converted audio file in kilobytes per second (kB/s). Value may be between 48 and 1,411. By default, the optimal bitrate will be chosen automatically.
try {
byte[] result = apiInstance.audioConvertToM4a(inputFile, fileUrl, bitRate);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AudioApi#audioConvertToM4a");
e.printStackTrace();
}
This second function is for converting files to AAC:
xxxxxxxxxx
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.AudioApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
AudioApi apiInstance = new AudioApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
String fileUrl = "fileUrl_example"; // String | Optional; URL of an audio file being used for conversion. Use this option for files larger than 2GB.
Integer bitRate = 56; // Integer | Optional; Specify the desired bitrate of the converted audio file in kilobytes per second (kB/s). Value may be between 48 and 1,411. By default, the optimal bitrate will be chosen automatically.
try {
byte[] result = apiInstance.audioConvertToAac(inputFile, fileUrl, bitRate);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AudioApi#audioConvertToAac");
e.printStackTrace();
}
As you can see, it is simple to choose and change your preferred output format, so your audio is always optimized for your needs.
For our final conversion function, to WAV, all of the major steps mimic our previous APIs. However, one small difference is that rather than specifying the desired bitrate for your output audio, you can instead choose a sample rate in kHz. This value may be between 8 and 96 kHz, with a standard of 44.1 kHz for CDs and 48 kHz for DVD audio. However, like before, if unspecified, the optimal sample rate will be chosen automatically. Now that we have clarified the small change to this API, we can once again install our library and call our function:
xxxxxxxxxx
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.AudioApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
AudioApi apiInstance = new AudioApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
String fileUrl = "fileUrl_example"; // String | Optional; URL of an audio file being used for conversion. Use this option for files larger than 2GB.
BigDecimal sampleRate = new BigDecimal(); // BigDecimal | Optional; Specify the desired sample rate of the converted audio file in kHz. Value may be between 8 and 96. Standard for audio CDs is 44.1, while DVD audio standard is 48. By default, the optimal sample rate will be chosen automatically.
try {
byte[] result = apiInstance.audioConvertToWav(inputFile, fileUrl, sampleRate);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AudioApi#audioConvertToWav");
e.printStackTrace();
}
Make your next media project stress free by allowing these APIs to automate it for you.
If you have any questions about using these APIs or inquiries concerning other API solutions, you can visit the Cloudmersive website where our team is happy to help with anything you might need.
Opinions expressed by DZone contributors are their own.
Comments