convert video to mp3 in csharp

To convert a video file to an MP3 file in C#, we can use the FFmpeg library. FFmpeg is a free, open-source software that can handle multimedia files, including video and audio. We will use the process class to run FFmpeg command-line tool which will convert videos to mp3.

To use FFmpeg in C#, we need to download the FFmpeg binaries and extract them to a folder. Then, we can use the following code to convert the video file to an MP3 file:

main.cs
using System.Diagnostics;

string videoFilePath = @"C:\path\to\video.mp4";
string outputFilePath = @"C:\path\to\output.mp3";

Process process = new Process();
process.StartInfo.FileName = @"C:\path\to\ffmpeg.exe";
process.StartInfo.Arguments = $"-i \"{videoFilePath}\" -vn -ar 44100 -ac 2 -b:a 192k \"{outputFilePath}\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;

process.Start();
process.WaitForExit();
544 chars
16 lines

In the code above, we first declare the paths for the video file and the output MP3 file. We then create a new process, set the FFmpeg executable as the process start file name, and pass the necessary arguments for the conversion. -i specifies the input video file path, -vn disables video processing, -ar sets the audio sample rate to 44100 Hz, -ac sets the number of audio channels to 2, -b:a sets the audio bitrate to 192k, and the output file path is specified as the last argument.

We also set the process start info to redirect the standard input and output streams and create no window. We start the process and wait for it to exit.

After running the code, the output file should be saved to the specified output file path in MP3 format.

gistlibby LogSnag