How to convert mp4 to mp3 in Android Java?

151 Views Asked by At

I have the mp4 link of a video but don't have a link for the mp3 version of that mp4 video. So is there any way that I can convert that mp4 video to mp3 in Android? I saw some resources but nothing works for me. I have two ways in which I believe this can be achieved

  1. Convert the mp4 link to mp3 directly. (Not Sure if this is achievable)
  2. Download the mp4 on the device with the help of a link and then use some code to convert that mp4 to mp3.

I also tried some solutions which are available online

https://github.com/tanersener/mobile-ffmpeg

I tried the above library to achieve the final goal. But got: Async command execution failed with returnCode=1.

This error in the code I am using is:

private class Mp4ToMp3ConverterTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        String mp4FilePath = params[0];
        String mp3OutputPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/output.mp3";

        String[] ffmpegCommand = {"-i", mp4FilePath, "-vn", "-ar", "44100", "-ac", "2", "-b:a", "192k", mp3OutputPath};


        Config.enableStatisticsCallback(new StatisticsCallback() {
            public void apply(Statistics newStatistics) {
                Log.d("Dekh", String.format("frame: %d, time: %d", newStatistics.getVideoFrameNumber(), newStatistics.getTime()));
            }
        });

        long executionIdd = FFmpeg.executeAsync(ffmpegCommand, new ExecuteCallback() {
            @Override
            public void apply(final long executionId, final int returnCode) {
                if (returnCode == RETURN_CODE_SUCCESS) {
                    Log.i("Dekh", "Async command execution completed successfully.");
                } else if (returnCode == RETURN_CODE_CANCEL) {
                    Log.i("Dekh", "Async command execution cancelled by user.");
                } else {
                    Log.i("Dekh", String.format("Async command execution failed with returnCode=%d.", returnCode));
                }
            }
        });

        FFmpeg.cancel(executionIdd);

        return mp3OutputPath;
    }
}

Solution number 2 which I used is:

https://androidprogrammatically425516919.wordpress.com/2020/04/21/how-to-convert-video-to-audio-in-android-programmatically/

But I got an error here also: Failed to instantiate extractor.
And another error is: java.io.FileNotFoundException: open failed: EISDIR (Is a directory)

I tried the online available solution to solve these errors but nothing worked. Such as granting write permission. Providing a valid location to save the output.

But nothing works so far. Please help me on this. Thank you.

0

There are 0 best solutions below