This application records microphone audio, detects silence, and transcribes speech into text using Whisper.net and NAudio. It supports multiple transcription modes: real-time, silence-aware, and WAV-file-based.
Use 16Khz Wav’s for a file feeds (FFMPEG).
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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
using NAudio.CoreAudioApi; using NAudio.Wave; using System; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Whisper.net; using Whisper.net.Ggml; using Whisper.net.Logger; //Install-Package Whisper.net.AllRuntimes //Install-Package NAudio //ffmpeg -i 111.mp3 -acodec pcm_s16le -ac 1 -ar 16000 out.wav namespace WhisperAudioToText { public partial class Form1 : Form { private WaveInEvent waveIn; private BufferedWaveProvider buffer; private WaveFileWriter writer; private string tempWavFile = Path.Combine(Path.GetTempPath(), "live.wav"); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //WAVToText(); //StartRealtimeIntervalWhisperAsync(); StartSilenceAwareWhisperAsync(); } private static async void WAVToText() { var ggmlType = GgmlType.Base; var modelFileName = "ggml-base.bin"; var wavFileName = @"D:\ffmpeg-7.1.1-full_build\bin\out.wav"; IDisposable whisperLogger = null; try { whisperLogger = LogProvider.AddConsoleLogging(WhisperLogLevel.Debug); if (!File.Exists(modelFileName)) { await DownloadModel(modelFileName, ggmlType); } using (var whisperFactory = WhisperFactory.FromPath(modelFileName)) using (var processor = whisperFactory.CreateBuilder() .WithLanguage("auto") .Build()) using (var fileStream = File.OpenRead(wavFileName)) { var results = processor.ProcessAsync(fileStream); var enumerator = results.GetAsyncEnumerator(); try { while (await enumerator.MoveNextAsync()) { var result = enumerator.Current; Console.WriteLine($"{result.Start}->{result.End}: {result.Text}"); } } finally { if (enumerator != null) await enumerator.DisposeAsync(); } } } finally { if (whisperLogger != null) whisperLogger.Dispose(); } } private bool _isRecording = false; private CancellationTokenSource _cancellationSource; private bool _isSilenceModeActive = false; private CancellationTokenSource _silenceToken; private const string modelFileName = "ggml-base.bin"; private async Task StartSilenceAwareWhisperAsync() { var ggmlType = GgmlType.Base; var silenceThreshold = 0.005f; var silenceDuration = TimeSpan.FromSeconds(1); //After one second of silence, process the request IDisposable whisperLogger = null; if (!File.Exists(modelFileName)) await DownloadModel(modelFileName, ggmlType); _isSilenceModeActive = true; _silenceToken = new CancellationTokenSource(); try { whisperLogger = LogProvider.AddConsoleLogging(WhisperLogLevel.None); // Disable verbose logs while (_isSilenceModeActive && !_silenceToken.IsCancellationRequested) { var waveFormat = new WaveFormat(16000, 1); var waveIn = new WaveInEvent { WaveFormat = waveFormat, BufferMilliseconds = 200 }; var chunkBuffer = new MemoryStream(); var writer = new WaveFileWriter(chunkBuffer, waveFormat); TimeSpan silenceTimer = TimeSpan.Zero; bool recordingStopped = false; EventHandler<WaveInEventArgs> dataAvailableHandler = (s, a) => { writer.Write(a.Buffer, 0, a.BytesRecorded); writer.Flush(); float maxVolume = GetMaxVolume(a.Buffer, a.BytesRecorded); if (maxVolume < silenceThreshold) { silenceTimer += TimeSpan.FromMilliseconds(waveIn.BufferMilliseconds); if (silenceTimer >= silenceDuration && !recordingStopped) { recordingStopped = true; waveIn.StopRecording(); } } else { silenceTimer = TimeSpan.Zero; } }; waveIn.DataAvailable += dataAvailableHandler; waveIn.StartRecording(); while (!recordingStopped && !_silenceToken.IsCancellationRequested) await Task.Delay(100); waveIn.DataAvailable -= dataAvailableHandler; writer.Flush(); byte[] audioData = chunkBuffer.ToArray(); writer.Dispose(); waveIn.Dispose(); if (IsSilent(audioData)) { //Debug.WriteLine("[Skipped silent chunk]"); continue; } // Transcribe in background using a dedicated processor _ = Task.Run(async () => { try { using (var whisperFactory = WhisperFactory.FromPath(modelFileName)) using (var taskProcessor = whisperFactory.CreateBuilder() .WithLanguage("auto") .Build()) using (var memoryStream = new MemoryStream(audioData)) { var results = taskProcessor.ProcessAsync(memoryStream); var enumerator = results.GetAsyncEnumerator(); try { while (await enumerator.MoveNextAsync()) { var result = enumerator.Current; Debug.WriteLine($"{DateTime.Now} {result.Start}->{result.End}: {result.Text}"); } } finally { await enumerator.DisposeAsync(); } } } catch (Exception ex) { Debug.WriteLine("Transcription Task Error: " + ex.Message); } }); } } finally { whisperLogger?.Dispose(); } } private bool IsSilent(byte[] buffer) { if (buffer == null || buffer.Length <= 44) return true; // Skip the first 44 bytes (WAV header) int offset = 44; double sumSquares = 0; int samples = (buffer.Length - offset) / 2; for (int i = offset; i < buffer.Length; i += 2) { short sample = BitConverter.ToInt16(buffer, i); double normalized = sample / 32768.0; sumSquares += normalized * normalized; } double rms = Math.Sqrt(sumSquares / samples); // Debug: Show RMS & first few bytes (optional) if (false) { Debug.WriteLine("RMS: " + rms.ToString("F6")); for (int i = 0; i < Math.Min(16, buffer.Length); i++) Debug.Write(buffer[i].ToString("X2") + " "); Debug.WriteLine(""); } // Silence if RMS is very low return rms < 0.001; } private float GetMaxVolume(byte[] buffer, int bytesRecorded) { float max = 0; for (int i = 0; i < bytesRecorded; i += 2) { short sample = BitConverter.ToInt16(buffer, i); float amplitude = Math.Abs(sample / 32768f); if (amplitude > max) max = amplitude; } return max; } private async Task StartRealtimeIntervalWhisperAsync() { var modelFileName = "ggml-base.bin"; var ggmlType = GgmlType.Base; IDisposable whisperLogger = null; try { whisperLogger = LogProvider.AddConsoleLogging(WhisperLogLevel.Warning); if (!File.Exists(modelFileName)) { await DownloadModel(modelFileName, ggmlType); } _isRecording = true; _cancellationSource = new CancellationTokenSource(); using (var whisperFactory = WhisperFactory.FromPath(modelFileName)) using (var processor = whisperFactory.CreateBuilder() .WithLanguage("auto") .Build()) { while (_isRecording && !_cancellationSource.IsCancellationRequested) { string chunkPath = Path.Combine(Path.GetTempPath(), "chunk_" + Guid.NewGuid().ToString("N") + ".wav"); await RecordChunkAsync(chunkPath, durationMs: 5000); using (var fileStream = File.OpenRead(chunkPath)) { var results = processor.ProcessAsync(fileStream); var enumerator = results.GetAsyncEnumerator(); try { while (await enumerator.MoveNextAsync()) { var result = enumerator.Current; Debug.WriteLine(result.Start + "->" + result.End + ": " + result.Text); } } finally { if (enumerator != null) await enumerator.DisposeAsync(); } } File.Delete(chunkPath); } } } finally { whisperLogger?.Dispose(); } } private async Task RecordChunkAsync(string filePath, int durationMs) { var waveFormat = new WaveFormat(16000, 1); var waveIn = new WaveInEvent { WaveFormat = waveFormat, BufferMilliseconds = 250 }; var buffer = new BufferedWaveProvider(waveFormat); var writer = new WaveFileWriter(filePath, waveFormat); waveIn.DataAvailable += (s, a) => { buffer.AddSamples(a.Buffer, 0, a.BytesRecorded); writer.Write(a.Buffer, 0, a.BytesRecorded); writer.Flush(); }; waveIn.StartRecording(); await Task.Delay(durationMs); waveIn.StopRecording(); writer.Dispose(); waveIn.Dispose(); } private void StopRealtimeWhisper() { _isRecording = false; _cancellationSource?.Cancel(); } private static async Task DownloadModel(string fileName, GgmlType ggmlType) { Console.WriteLine($"Downloading Model {fileName}"); using (var modelStream = await WhisperGgmlDownloader.Default.GetGgmlModelAsync(ggmlType)) using (var fileWriter = File.OpenWrite(fileName)) { await modelStream.CopyToAsync(fileWriter); } } } } |