-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMainWindow.xaml.cs
280 lines (240 loc) · 10.7 KB
/
MainWindow.xaml.cs
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using Microsoft.Win32;
using Serilog; // Assuming Serilog is used for logging
namespace NoSilence
{
public partial class MainWindow : Window
{
private string ffmpegPath;
private string selectedFilePath;
private string selectedOutputFolder;
private int silenceThreshold = 60; // Default value
public MainWindow()
{
InitializeComponent();
// Initialize Serilog or any other logger here if needed
Log.Information("Application started.");
ffmpegPath = ffmpegPathTextBox.Text; // Initialize FFmpeg path from the TextBox
}
private void BrowseFFmpeg_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog
{
Filter = "Executable Files (*.exe)|*.exe",
Title = "Select FFmpeg Executable"
};
if (openFileDialog.ShowDialog() == true)
{
ffmpegPath = openFileDialog.FileName;
ffmpegPathTextBox.Text = ffmpegPath;
Log.Information("FFmpeg path set to: {FFmpegPath}", ffmpegPath);
}
}
private void Window_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
if (Path.GetExtension(file).ToLower() == ".mp3")
{
fileList.Items.Add(file);
Log.Information("File added: {FilePath}", file);
}
}
}
}
private void FileList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (fileList.SelectedItem != null)
{
selectedFilePath = fileList.SelectedItem.ToString();
Log.Information("File selected: {SelectedFilePath}", selectedFilePath);
}
}
private void Preview_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(selectedFilePath) || !File.Exists(selectedFilePath))
{
MessageBox.Show("Please select an MP3 file to preview.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
// Pass the FFmpeg path to the PreviewWindow constructor
PreviewWindow previewWindow = new PreviewWindow(selectedFilePath, ffmpegPath);
previewWindow.Show();
}
private async void RemoveSilence_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(ffmpegPath) || !File.Exists(ffmpegPath))
{
MessageBox.Show("Please specify a valid FFmpeg executable path.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (fileList.Items.Count == 0)
{
MessageBox.Show("Please select at least one MP3 file to process.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
// Ask user for output directory
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result != System.Windows.Forms.DialogResult.OK || string.IsNullOrWhiteSpace(dialog.SelectedPath))
{
return;
}
selectedOutputFolder = dialog.SelectedPath;
}
processingProgressBar.Maximum = fileList.Items.Count;
processingProgressBar.Value = 0;
bool overwriteAll = false;
foreach (string filePath in fileList.Items)
{
if (!File.Exists(filePath))
{
MessageBox.Show($"File does not exist: {filePath}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
continue;
}
string outputFilePath = Path.Combine(selectedOutputFolder, Path.GetFileName(filePath));
currentFileLabel.Content = $"Processing: {Path.GetFileName(filePath)}";
if (File.Exists(outputFilePath))
{
if (!overwriteAll)
{
var overwriteDialog = new OverwriteDialog(Path.GetFileName(outputFilePath));
overwriteDialog.Owner = this; // Set owner for modal behavior
overwriteDialog.ShowDialog();
switch (overwriteDialog.Result)
{
case OverwriteDialogResult.Yes:
File.Delete(outputFilePath);
break;
case OverwriteDialogResult.YesToAll:
overwriteAll = true;
File.Delete(outputFilePath);
break;
case OverwriteDialogResult.No:
continue;
case OverwriteDialogResult.Cancel:
return;
}
}
else
{
File.Delete(outputFilePath);
}
}
// Run FFmpeg and update progress
await Task.Run(() => RunFFmpegProcess(filePath, outputFilePath, silenceThreshold));
processingProgressBar.Value++;
}
MessageBox.Show("Processing completed.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
currentFileLabel.Content = "Processing: Completed";
// open the outputFilePath folder
// Open the outputFilePath folder
Process.Start("explorer.exe", $"/select,\"{selectedOutputFolder}\"");
fileList.Items.Clear();
//clear the fileList in the ui
}
private void RunFFmpegProcess(string inputFilePath, string outputFilePath, int silenceThreshold)
{
try
{
// Step 1: Extract the bitrate of the input file
string bitrate = GetBitrate(inputFilePath);
// Step 2: Prepare FFmpeg command with extracted bitrate
string arguments = $"-i \"{inputFilePath}\" -b:a {bitrate} -af silenceremove=start_periods=1:start_duration=1:start_threshold=-{silenceThreshold}dB:detection=peak,aformat=dblp,areverse,silenceremove=start_periods=1:start_duration=1:start_threshold=-{silenceThreshold}dB:detection=peak,aformat=dblp,areverse \"{outputFilePath}\"";
Process ffmpegProcess = new Process();
ffmpegProcess.StartInfo.FileName = ffmpegPath;
ffmpegProcess.StartInfo.Arguments = arguments;
ffmpegProcess.StartInfo.UseShellExecute = false;
ffmpegProcess.StartInfo.RedirectStandardOutput = true;
ffmpegProcess.StartInfo.RedirectStandardError = true;
ffmpegProcess.StartInfo.CreateNoWindow = true;
ffmpegProcess.OutputDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Dispatcher.BeginInvoke(new Action(() =>
{
outputTextBox.AppendText(e.Data + Environment.NewLine);
outputTextBox.ScrollToEnd();
}));
}
};
ffmpegProcess.ErrorDataReceived += (sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Dispatcher.BeginInvoke(new Action(() =>
{
outputTextBox.AppendText(e.Data + Environment.NewLine);
outputTextBox.ScrollToEnd();
}));
}
};
ffmpegProcess.Start();
ffmpegProcess.BeginOutputReadLine();
ffmpegProcess.BeginErrorReadLine();
ffmpegProcess.WaitForExit();
}
catch (Exception ex)
{
MessageBox.Show($"Error running FFmpeg: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
Log.Error(ex, "Error running FFmpeg");
}
}
private void Load_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog
{
Filter = "MP3 Files (*.mp3)|*.mp3",
Multiselect = true,
Title = "Select MP3 Files"
};
if (openFileDialog.ShowDialog() == true)
{
foreach (string file in openFileDialog.FileNames)
{
fileList.Items.Add(file);
Log.Information("File added: {FilePath}", file);
}
}
}
private string GetBitrate(string inputFilePath)
{
try
{
Process ffmpegProcess = new Process();
ffmpegProcess.StartInfo.FileName = ffmpegPath;
ffmpegProcess.StartInfo.Arguments = $"-i \"{inputFilePath}\"";
ffmpegProcess.StartInfo.UseShellExecute = false;
ffmpegProcess.StartInfo.RedirectStandardError = true;
ffmpegProcess.StartInfo.CreateNoWindow = true;
ffmpegProcess.Start();
string output = ffmpegProcess.StandardError.ReadToEnd();
ffmpegProcess.WaitForExit();
// Parse the output to find the bitrate
var bitrateLine = output.Split('\n').FirstOrDefault(line => line.Contains("bitrate"));
if (!string.IsNullOrEmpty(bitrateLine))
{
var match = System.Text.RegularExpressions.Regex.Match(bitrateLine, @"bitrate:\s*(\d+)\s*kb/s");
if (match.Success)
{
return match.Groups[1].Value + "k";
}
}
}
catch (Exception ex)
{
Log.Error(ex, "Error extracting bitrate from file: {FilePath}", inputFilePath);
}
// Default bitrate if extraction fails
return "192k";
}
}
}