-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAudioExtractor.cs
More file actions
175 lines (151 loc) · 7.25 KB
/
Copy pathAudioExtractor.cs
File metadata and controls
175 lines (151 loc) · 7.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.IO;
using NAudio.Wave;
namespace SubtitleCreator
{
/// <summary>
/// Extracts audio from a video file.
/// </summary>
public static class AudioExtractor
{
private const string fileNameIdentifier = "_!SubtitleCreator!";
private static string outputFilePath = string.Empty;
/// <summary>
/// Enry point to extract the audio fromthe video file so Whisper can process it.
/// </summary>
/// <param name="videoFilePath"></param>
/// <param name="attemptRepair"></param>
/// <param name="ffmpegPath"></param>
/// <returns></returns>
public static string ExtractAudioFromVideoFile(string videoFilePath, bool attemptRepair, string ffmpegPath)
{
string newVideoFilePath = videoFilePath;
bool tempFileCreated = false;
if (Path.GetExtension(videoFilePath).ToLower() == ".mkv")
{
Utilities.ConsoleWithLog("Input file is in a MKV container. Extracting the video.");
newVideoFilePath = ExtractVideoFromMKV(videoFilePath, ffmpegPath);
Utilities.ConsoleWithLog("The video file has been extracted. Now let's get back to extracting its audio.");
tempFileCreated = true;
}
outputFilePath = Path.Combine(Path.GetDirectoryName(videoFilePath) ?? string.Empty, $"{Path.GetFileNameWithoutExtension(videoFilePath)}{fileNameIdentifier}.wav");
try
{
ExtractTheAudio(newVideoFilePath);
}
catch (Exception ex)
{
if (!ex.Message.ToLower().Contains("media type is invalid"))
{
Utilities.ConsoleWithLog($"Unrecoverable exception extracting audio from the video file. {ex.Message}");
Utilities.ConsoleWithLog("Not attempting to repair.");
outputFilePath = string.Empty;
}
else
if (attemptRepair == false)
{
Utilities.ConsoleWithLog($"Exception extracting audio from the video file. {ex.Message}");
Utilities.ConsoleWithLog("Not attempting to repair.");
outputFilePath = string.Empty;
}
else
if (string.IsNullOrEmpty(ffmpegPath))
{
Utilities.ConsoleWithLog($"Exception extracting audio from the video file and ffmpegPath not specified. {ex.Message}");
Utilities.ConsoleWithLog("Not attempting to repair.");
outputFilePath = string.Empty;
}
else
{
Utilities.ConsoleWithLog($"Exception extracting audio from the video file. {ex.Message}");
Utilities.ConsoleWithLog("Attempting to repair.");
string repairedFile = RepairAudio(videoFilePath, ffmpegPath);
try
{
ExtractTheAudio(repairedFile);
}
catch (Exception ex2)
{
Utilities.ConsoleWithLog($"Exception extracting audio from the repaired video file. {ex2.Message}");
outputFilePath = string.Empty;
}
finally
{
File.Delete(repairedFile);
}
}
}
if (tempFileCreated == true)
File.Delete(newVideoFilePath);
return outputFilePath;
}
/// <summary>
/// Perform the actual audio extraction.
/// </summary>
/// <param name="videoFilePath"></param>
private static void ExtractTheAudio(string videoFilePath)
{
const int outRate = 16000;
using (var reader = new MediaFoundationReader(videoFilePath))
{
WaveFormat outFormat = new WaveFormat(outRate, reader.WaveFormat.Channels);
using (var resampler = new MediaFoundationResampler(reader, outFormat))
{
resampler.ResamplerQuality = 60; // Adjust quality if needed
WaveFileWriter.CreateWaveFile(outputFilePath, resampler);
}
}
}
/// <summary>
/// Attempt to repair the audio in the video file. This is a last ditch effort to get the audio extracted. If this fails, the audio extraction will fail.
/// </summary>
/// <param name="videoFilePath"></param>
/// <param name="ffmpegPath"></param>
/// <returns></returns>
private static string RepairAudio(string videoFilePath, string ffmpegPath)
{
// repair audio ffmpeg" -i "NFL Fantasy Live 2024_09_20_18_00_00.ts" -c:v copy -c:a aac "NFL Fantasy Live 2024_09_20_18_00_00.mp4"
string intermediateFilePath = Path.Combine(Path.GetDirectoryName(videoFilePath) ?? string.Empty, $"{Path.GetFileNameWithoutExtension(videoFilePath)}{fileNameIdentifier}.mp4");
string ffmpegArgs = $"-i \"{videoFilePath}\" -c:v copy -c:a aac \"{intermediateFilePath}\"";
// Set up the process to run FFmpeg
using (Process ffmpeg = new Process())
{
ffmpeg.StartInfo.FileName = $"\"{ffmpegPath}\\ffmpeg\"";
ffmpeg.StartInfo.Arguments = ffmpegArgs;
ffmpeg.StartInfo.RedirectStandardError = true;
ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.CreateNoWindow = true;
// Start the process
ffmpeg.Start();
// Read the output
string output = ffmpeg.StandardError.ReadToEnd();
ffmpeg.WaitForExit();
}
return intermediateFilePath;
}
private static string ExtractVideoFromMKV(string videoFilePath, string ffmpegPath)
{
// check for mkv input file and use ffmpeg to convert to mp4 ffmpeg -i input.mkv -c copy -map 0:v -map 0:a output_video.mp4
string intermediateFilePath = Path.Combine(Path.GetDirectoryName(videoFilePath) ?? string.Empty, $"{Path.GetFileNameWithoutExtension(videoFilePath)}{fileNameIdentifier}.mp4");
string ffmpegArgs = $"-i \"{videoFilePath}\" -c copy -map 0:v -map 0:a \"{intermediateFilePath}\"";
// Set up the process to run FFmpeg
using (Process ffmpeg = new Process())
{
ffmpeg.StartInfo.FileName = $"\"{ffmpegPath}\\ffmpeg\"";
ffmpeg.StartInfo.Arguments = ffmpegArgs;
ffmpeg.StartInfo.RedirectStandardError = true;
ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.CreateNoWindow = true;
// Start the process
ffmpeg.Start();
// Read the output
string output = ffmpeg.StandardError.ReadToEnd();
ffmpeg.WaitForExit();
}
return intermediateFilePath;
}
}
}