-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainForm.cs
More file actions
1660 lines (1471 loc) · 67.7 KB
/
MainForm.cs
File metadata and controls
1660 lines (1471 loc) · 67.7 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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NAudio.Wave;
using Google.GenAI;
using Google.Cloud.AIPlatform.V1;
using Google.Cloud.VertexAI.Extensions;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;
using Sdk = OpenAI.Realtime;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RealtimePlayGround
{
public partial class MainForm : Form
{
private WaveIn? _waveIn;
private WaveOutEvent? _waveOut;
private AudioFileReader? _audioFileReader;
private bool _isRecording = false;
private string _audioFilePath = Path.Combine(Path.GetTempPath(), "recorded_audio.wav");
private WaveFileWriter? _waveFileWriter;
private WaveFormat? _recordingFormat;
private System.Drawing.Image? _microphoneIcon;
private System.Drawing.Image? _muteIcon;
private System.Drawing.Image? _startPlayIcon;
private System.Drawing.Image? _stopPlayIcon;
private System.Drawing.Image? _startCallIcon;
private System.Drawing.Image? _hangUpIcon;
private IRealtimeClient? _realtimeClient;
private IRealtimeClientSession? _realtimeSession;
private bool _isCallActive = false;
private BufferedWaveProvider? _audioProvider;
// Client messages are sent directly via _realtimeSession.SendAsync
private CancellationTokenSource? _streamingCancellationTokenSource;
private ActivityListener? _activityListener;
private MeterListener? _meterListener;
private readonly object _recordingLock = new();
private volatile bool _dataReceivedFlag;
private int _selectedDeviceNumber = 0;
private int _workingSampleRate = 44100;
public MainForm()
{
InitializeComponent();
LoadIcons();
SetupTelemetryListeners();
InitializeAudioDevice();
}
private void InitializeAudioDevice()
{
// Find and validate available recording devices at startup
try
{
int deviceCount = WaveIn.DeviceCount;
System.Diagnostics.Debug.WriteLine($"Found {deviceCount} recording devices");
if (deviceCount > 0)
{
// List all devices
for (int i = 0; i < deviceCount; i++)
{
var capabilities = WaveIn.GetCapabilities(i);
System.Diagnostics.Debug.WriteLine($"Audio device {i}: {capabilities.ProductName}, Channels: {capabilities.Channels}");
}
// Use device 0 (default)
_selectedDeviceNumber = 0;
var selectedDevice = WaveIn.GetCapabilities(_selectedDeviceNumber);
statusLabel.Text = $"Ready. Device: {selectedDevice.ProductName}";
// Test which sample rate works
TestSampleRates();
}
else
{
statusLabel.Text = "No microphone detected.";
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error initializing audio device: {ex.Message}");
statusLabel.Text = "Error detecting microphone.";
}
}
private void TestSampleRates()
{
// Test sample rates at startup to find one that works
int[] sampleRates = [44100, 48000, 16000, 24000, 22050, 8000];
foreach (var rate in sampleRates)
{
try
{
using var testWaveIn = new WaveIn
{
DeviceNumber = _selectedDeviceNumber,
WaveFormat = new WaveFormat(rate, 16, 1)
};
// If we get here without exception, this rate works
_workingSampleRate = rate;
System.Diagnostics.Debug.WriteLine($"Sample rate {rate}Hz works for this device");
return;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Sample rate {rate}Hz failed: {ex.Message}");
}
}
}
private void SetupTelemetryListeners()
{
// Set up ActivityListener to capture Activity stop events
_activityListener = new ActivityListener
{
// Listen to activities from Microsoft.Extensions.AI sources
ShouldListenTo = source => source.Name.StartsWith("Microsoft.Extensions.AI") ||
source.Name.StartsWith("OpenAI") ||
source.Name.StartsWith("Experimental.Microsoft.Extensions.AI"),
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllDataAndRecorded,
ActivityStopped = activity =>
{
WriteActivityToLog(activity);
}
};
ActivitySource.AddActivityListener(_activityListener);
// Set up MeterListener to capture metrics
_meterListener = new MeterListener();
_meterListener.InstrumentPublished = (instrument, listener) =>
{
// Listen to metrics from Microsoft.Extensions.AI sources
if (instrument.Meter.Name.StartsWith("Microsoft.Extensions.AI") ||
instrument.Meter.Name.StartsWith("OpenAI") ||
instrument.Meter.Name.StartsWith("Experimental.Microsoft.Extensions.AI"))
{
listener.EnableMeasurementEvents(instrument);
}
};
// Handle different measurement types
_meterListener.SetMeasurementEventCallback<long>(OnMeasurementRecorded);
_meterListener.SetMeasurementEventCallback<int>(OnMeasurementRecorded);
_meterListener.SetMeasurementEventCallback<double>(OnMeasurementRecorded);
_meterListener.SetMeasurementEventCallback<float>(OnMeasurementRecorded);
_meterListener.Start();
}
private void WriteActivityToLog(Activity activity)
{
if (richTextBoxLogs == null || richTextBoxLogs.IsDisposed)
return;
var sb = new StringBuilder();
sb.AppendLine($"[Activity] {activity.OperationName}");
sb.AppendLine($" Duration: {activity.Duration.TotalMilliseconds:F2}ms");
sb.AppendLine($" Status: {activity.Status}");
if (activity.Tags.Any())
{
sb.AppendLine(" Tags:");
foreach (var tag in activity.Tags)
{
// Truncate long values for readability
var value = tag.Value?.Length > 100 ? tag.Value[..100] + "..." : tag.Value;
sb.AppendLine($" {tag.Key}: {value}");
}
}
if (activity.Events.Any())
{
sb.AppendLine(" Events:");
foreach (var evt in activity.Events)
{
sb.AppendLine($" {evt.Name} @ {evt.Timestamp:HH:mm:ss.fff}");
foreach (var evtTag in evt.Tags)
{
var value = evtTag.Value?.ToString();
if (value?.Length > 100)
value = value[..100] + "...";
sb.AppendLine($" {evtTag.Key}: {value}");
}
}
}
WriteToLogRichTextBox(sb.ToString(), System.Drawing.Color.Purple);
}
private void OnMeasurementRecorded<T>(Instrument instrument, T measurement, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state)
{
var sb = new StringBuilder();
sb.Append($"[Metric] {instrument.Meter.Name}/{instrument.Name}: {measurement} {instrument.Unit}");
if (tags.Length > 0)
{
sb.Append(" | Tags: ");
var tagStrings = new List<string>();
foreach (var tag in tags)
{
tagStrings.Add($"{tag.Key}={tag.Value}");
}
sb.Append(string.Join(", ", tagStrings));
}
WriteToLogRichTextBox(sb.ToString(), System.Drawing.Color.Teal);
}
private void WriteToLogRichTextBox(string message, System.Drawing.Color color)
{
if (richTextBoxLogs == null || richTextBoxLogs.IsDisposed)
return;
if (richTextBoxLogs.InvokeRequired)
{
richTextBoxLogs.BeginInvoke(() => AppendLogText(message, color));
}
else
{
AppendLogText(message, color);
}
}
private void AppendLogText(string message, System.Drawing.Color color)
{
try
{
if (richTextBoxLogs.IsDisposed)
return;
int startIndex = richTextBoxLogs.TextLength;
richTextBoxLogs.AppendText(message + Environment.NewLine);
richTextBoxLogs.Select(startIndex, message.Length);
richTextBoxLogs.SelectionColor = color;
richTextBoxLogs.Select(richTextBoxLogs.TextLength, 0);
richTextBoxLogs.SelectionColor = richTextBoxLogs.ForeColor;
richTextBoxLogs.ScrollToCaret();
}
catch (ObjectDisposedException)
{
// Control was disposed, ignore
}
}
private void LoadIcons()
{
try
{
string basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources");
string micPath = Path.Combine(basePath, "microphone.png");
string mutePath = Path.Combine(basePath, "mute.png");
string startPlayPath = Path.Combine(basePath, "start-play.png");
string stopPlayPath = Path.Combine(basePath, "stop-play.png");
string startCallPath = Path.Combine(basePath, "start-call.png");
string hangUpPath = Path.Combine(basePath, "hang-up.png");
if (File.Exists(micPath))
{
_microphoneIcon = System.Drawing.Image.FromFile(micPath);
// Resize icon to fit button nicely
_microphoneIcon = new System.Drawing.Bitmap(_microphoneIcon, new System.Drawing.Size(32, 32));
}
if (File.Exists(mutePath))
{
_muteIcon = System.Drawing.Image.FromFile(mutePath);
// Resize icon to fit button nicely
_muteIcon = new System.Drawing.Bitmap(_muteIcon, new System.Drawing.Size(32, 32));
}
if (File.Exists(startPlayPath))
{
_startPlayIcon = System.Drawing.Image.FromFile(startPlayPath);
// Resize icon to fit button nicely
_startPlayIcon = new System.Drawing.Bitmap(_startPlayIcon, new System.Drawing.Size(32, 32));
}
if (File.Exists(stopPlayPath))
{
_stopPlayIcon = System.Drawing.Image.FromFile(stopPlayPath);
// Resize icon to fit button nicely
_stopPlayIcon = new System.Drawing.Bitmap(_stopPlayIcon, new System.Drawing.Size(32, 32));
}
if (File.Exists(startCallPath))
{
_startCallIcon = System.Drawing.Image.FromFile(startCallPath);
// Resize icon to fit button nicely
_startCallIcon = new System.Drawing.Bitmap(_startCallIcon, new System.Drawing.Size(32, 32));
}
if (File.Exists(hangUpPath))
{
_hangUpIcon = System.Drawing.Image.FromFile(hangUpPath);
// Resize icon to fit button nicely
_hangUpIcon = new System.Drawing.Bitmap(_hangUpIcon, new System.Drawing.Size(32, 32));
}
// Set initial icon
if (_microphoneIcon != null)
{
btnRecord.Image = _microphoneIcon;
btnRecord.ImageAlign = System.Drawing.ContentAlignment.MiddleCenter;
btnRecord.Text = string.Empty;
}
if (_startPlayIcon != null)
{
btnPlay.Image = _startPlayIcon;
btnPlay.ImageAlign = System.Drawing.ContentAlignment.MiddleCenter;
}
if (_startCallIcon != null)
{
btnCall.Image = _startCallIcon;
btnCall.ImageAlign = System.Drawing.ContentAlignment.MiddleCenter;
}
}
catch (Exception)
{
// Silently fail if icons can't be loaded
}
}
private async void btnRecord_Click(object sender, EventArgs e)
{
if (!_isRecording)
{
await StartRecordingAsync();
}
else
{
StopRecording();
}
}
private async Task StartRecordingAsync()
{
const int maxAttempts = 3;
try
{
btnRecord.Enabled = false;
btnPlay.Enabled = false;
// Stop and discard any ongoing audio playback
if (_waveOut?.PlaybackState == PlaybackState.Playing)
{
_waveOut.Stop();
}
_audioProvider?.ClearBuffer();
statusLabel.Text = "Starting recording...";
// Check available devices
int deviceCount = WaveIn.DeviceCount;
if (deviceCount == 0)
{
throw new InvalidOperationException("No recording devices found.");
}
for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
// Clean up any existing resources before each attempt
StopAndDisposeWaveIn();
CleanupRecordingResources();
if (attempt > 1)
{
statusLabel.Text = $"Retrying recording (attempt {attempt}/{maxAttempts})...";
// Brief pause between retries to let the device fully release
await Task.Delay(200).ConfigureAwait(true);
}
// Prepare file path
_audioFilePath = Path.Combine(Path.GetTempPath(), $"recorded_audio_{DateTime.Now:yyyyMMdd_HHmmss}.wav");
// Configure recording format using the working sample rate
_recordingFormat = new WaveFormat(_workingSampleRate, 16, 1);
_waveIn = new WaveIn
{
DeviceNumber = _selectedDeviceNumber,
WaveFormat = _recordingFormat,
BufferMilliseconds = 100,
NumberOfBuffers = 3
};
// Create WAV file writer
_waveFileWriter = new WaveFileWriter(_audioFilePath, _recordingFormat);
// Hook up the data available event
_waveIn.DataAvailable += WaveIn_DataAvailable;
_waveIn.RecordingStopped += WaveIn_RecordingStopped;
// Reset verification flag and start recording
_dataReceivedFlag = false;
_waveIn.StartRecording();
// Yield the UI thread so the WaveIn message pump callbacks can fire.
// WaveIn delivers data via Windows messages — Task.Delay lets the
// message loop process them, unlike Thread.Sleep which blocks.
for (int i = 0; i < 10 && !_dataReceivedFlag; i++)
{
await Task.Delay(100).ConfigureAwait(true);
}
if (_dataReceivedFlag)
{
// Recording is verified — data is flowing
_isRecording = true;
if (_muteIcon != null)
btnRecord.Image = _muteIcon;
trackSpeed.Enabled = false;
btnRecord.Enabled = true;
statusLabel.Text = $"Recording at {_workingSampleRate}Hz... Speak now!";
System.Diagnostics.Debug.WriteLine($"Recording started at {_workingSampleRate}Hz (attempt {attempt})");
return;
}
// Data didn't flow — retry
System.Diagnostics.Debug.WriteLine($"Recording attempt {attempt}/{maxAttempts}: no data received, retrying...");
}
// All attempts failed
StopAndDisposeWaveIn();
CleanupRecordingResources();
throw new InvalidOperationException(
$"Microphone did not produce audio data after {maxAttempts} attempts.");
}
catch (Exception ex)
{
_isRecording = false;
StopAndDisposeWaveIn();
CleanupRecordingResources();
MessageBox.Show(
$"Error starting recording: {ex.Message}\n\nPlease check:\n" +
"1. Microphone is connected\n" +
"2. Microphone permissions are enabled\n" +
"3. No other app is using the microphone",
"Recording Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
statusLabel.Text = "Recording failed.";
if (_microphoneIcon != null)
btnRecord.Image = _microphoneIcon;
btnRecord.Enabled = true;
}
}
private void WaveIn_DataAvailable(object? sender, WaveInEventArgs e)
{
try
{
if (_waveFileWriter != null && e.BytesRecorded > 0)
{
_dataReceivedFlag = true;
_waveFileWriter.Write(e.Buffer, 0, e.BytesRecorded);
// Calculate peak level for visual feedback
float maxLevel = 0;
for (int i = 0; i < e.BytesRecorded - 1; i += 2)
{
short sample = (short)(e.Buffer[i] | (e.Buffer[i + 1] << 8));
float level = Math.Abs(sample / 32768f);
if (level > maxLevel) maxLevel = level;
}
// Update UI (throttled)
long length = _waveFileWriter.Length;
if (length % 8000 < e.BytesRecorded)
{
BeginInvoke(() =>
{
string indicator = maxLevel > 0.05f ? "🔊 Sound detected" : "🎤 Listening...";
statusLabel.Text = $"Recording... {length / 1024}KB | {indicator}";
});
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error in DataAvailable: {ex.Message}");
}
}
private void WaveIn_RecordingStopped(object? sender, StoppedEventArgs e)
{
if (e.Exception != null)
{
System.Diagnostics.Debug.WriteLine($"Recording stopped with error: {e.Exception.Message}");
BeginInvoke(() =>
{
statusLabel.Text = $"Recording error: {e.Exception.Message}";
});
}
}
private void StopRecording()
{
try
{
btnRecord.Enabled = false;
statusLabel.Text = "Stopping recording...";
_isRecording = false;
// Stop and dispose WaveIn
StopAndDisposeWaveIn();
// Close the file writer
CleanupRecordingResources();
// Reset button
if (_microphoneIcon != null)
btnRecord.Image = _microphoneIcon;
// Re-enable speed control if session is active (OpenAI only)
if (_isCallActive && cmbProvider.SelectedIndex == 0)
trackSpeed.Enabled = true;
else
trackSpeed.Enabled = false;
btnRecord.Enabled = true;
// Check file
if (File.Exists(_audioFilePath))
{
var fileInfo = new FileInfo(_audioFilePath);
long audioBytes = fileInfo.Length - 44; // Subtract WAV header
if (audioBytes > 0)
{
btnPlay.Enabled = true;
statusLabel.Text = $"Recorded {audioBytes / 1024}KB of audio.";
// Send to API if connected
if (_realtimeSession != null && _isCallActive)
{
_ = SendAudioToAPIAsync();
}
}
else
{
statusLabel.Text = "No audio captured. Check microphone.";
btnPlay.Enabled = false;
}
}
else
{
statusLabel.Text = "Recording failed - no file created.";
btnPlay.Enabled = false;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error stopping recording: {ex.Message}");
statusLabel.Text = "Error stopping recording.";
btnRecord.Enabled = true;
if (_microphoneIcon != null)
btnRecord.Image = _microphoneIcon;
}
}
private void StopAndDisposeWaveIn()
{
if (_waveIn != null)
{
try
{
_waveIn.DataAvailable -= WaveIn_DataAvailable;
_waveIn.RecordingStopped -= WaveIn_RecordingStopped;
_waveIn.StopRecording();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error stopping WaveIn: {ex.Message}");
}
finally
{
try
{
_waveIn.Dispose();
}
catch { }
_waveIn = null;
}
}
}
private void CleanupRecordingResources()
{
if (_waveFileWriter != null)
{
try
{
_waveFileWriter.Flush();
_waveFileWriter.Dispose();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error closing file writer: {ex.Message}");
}
finally
{
_waveFileWriter = null;
}
}
_recordingFormat = null;
}
private async Task SendAudioToAPIAsync()
{
if (_realtimeSession == null || !_isCallActive)
{
statusLabel.Text = "Not connected.";
return;
}
if (!File.Exists(_audioFilePath))
{
statusLabel.Text = "No audio file found.";
return;
}
try
{
statusLabel.Text = "Sending audio...";
// Read the audio file
byte[] audioData;
WaveFormat format;
using (var reader = new WaveFileReader(_audioFilePath))
{
format = reader.WaveFormat;
using var ms = new MemoryStream();
byte[] buffer = new byte[reader.WaveFormat.AverageBytesPerSecond];
int bytesRead;
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
audioData = ms.ToArray();
}
if (audioData.Length == 0)
{
statusLabel.Text = "No audio data captured.";
return;
}
// Convert to mono PCM16 at the target sample rate
// OpenAI: 24kHz, Gemini/Bedrock/VertexAI: 16kHz
bool isBedrock = cmbProvider.SelectedIndex == 2;
bool isGeminiProvider = cmbProvider.SelectedIndex == 1;
bool isVertexAIProvider = cmbProvider.SelectedIndex == 3;
int targetSampleRate = (isBedrock || isGeminiProvider || isVertexAIProvider) ? 16000 : 24000;
byte[] monoAudio = ConvertToMono(audioData, format.Channels);
byte[] resampledAudio = ResampleAudio(monoAudio, format.SampleRate, targetSampleRate);
// Check minimum length (100ms)
int minBytes = targetSampleRate * 2 / 10; // 100ms at 16-bit mono
if (resampledAudio.Length < minBytes)
{
double durationMs = (resampledAudio.Length / 2.0) / targetSampleRate * 1000.0;
statusLabel.Text = $"Audio too short ({durationMs:F0}ms). Need 100ms+.";
return;
}
double audioDurationMs = (resampledAudio.Length / 2.0) / targetSampleRate * 1000.0;
if (_realtimeSession != null)
{
// Clear logs to avoid performance degradation with verbose logging
richTextBoxLogs?.Clear();
var ct = _streamingCancellationTokenSource?.Token ?? default;
await _realtimeSession.SendAsync(new InputAudioBufferAppendRealtimeClientMessage(
audioContent: new DataContent($"data:audio/pcm;base64,{Convert.ToBase64String(resampledAudio)}")
), ct);
await _realtimeSession.SendAsync(new InputAudioBufferCommitRealtimeClientMessage(), ct);
await _realtimeSession.SendAsync(new CreateResponseRealtimeClientMessage(), ct);
statusLabel.Text = $"Sent {audioDurationMs:F0}ms of audio.";
}
}
catch (Exception ex)
{
WriteErrorToRichTextBox($"Error sending audio: {ex.Message}");
statusLabel.Text = "Error sending audio.";
}
}
private byte[] ConvertToMono(byte[] audioData, int channels)
{
if (channels <= 1)
return audioData;
if (channels != 2)
throw new NotSupportedException($"Unsupported channel count: {channels}");
byte[] monoData = new byte[audioData.Length / 2];
for (int i = 0; i < audioData.Length - 3; i += 4)
{
short left = BitConverter.ToInt16(audioData, i);
short right = BitConverter.ToInt16(audioData, i + 2);
short mono = (short)((left + right) / 2);
byte[] monoBytes = BitConverter.GetBytes(mono);
int destIndex = i / 2;
monoData[destIndex] = monoBytes[0];
monoData[destIndex + 1] = monoBytes[1];
}
return monoData;
}
private byte[] ResampleAudio(byte[] input, int inputRate, int outputRate)
{
if (inputRate == outputRate)
return input;
int inputSamples = input.Length / 2;
int outputSamples = (int)((long)inputSamples * outputRate / inputRate);
byte[] output = new byte[outputSamples * 2];
for (int i = 0; i < outputSamples; i++)
{
double sourceIndex = (double)i * inputSamples / outputSamples;
int index1 = (int)sourceIndex;
int index2 = Math.Min(index1 + 1, inputSamples - 1);
double fraction = sourceIndex - index1;
short sample1 = BitConverter.ToInt16(input, index1 * 2);
short sample2 = BitConverter.ToInt16(input, index2 * 2);
short interpolated = (short)(sample1 + (sample2 - sample1) * fraction);
byte[] bytes = BitConverter.GetBytes(interpolated);
output[i * 2] = bytes[0];
output[i * 2 + 1] = bytes[1];
}
return output;
}
private void btnPlay_Click(object sender, EventArgs e)
{
if (!File.Exists(_audioFilePath))
{
MessageBox.Show("No audio file to play.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
try
{
if (_waveOut?.PlaybackState == PlaybackState.Playing)
{
_waveOut.Stop();
_waveOut.Dispose();
_waveOut = null;
_audioFileReader?.Dispose();
_audioFileReader = null;
if (_startPlayIcon != null)
btnPlay.Image = _startPlayIcon;
statusLabel.Text = "Playback stopped.";
}
else
{
_waveOut?.Dispose();
_audioFileReader?.Dispose();
_waveOut = new WaveOutEvent();
_audioFileReader = new AudioFileReader(_audioFilePath);
_waveOut.Init(_audioFileReader);
_waveOut.PlaybackStopped += (s, args) =>
{
_audioFileReader?.Dispose();
_audioFileReader = null;
Invoke(() =>
{
if (_startPlayIcon != null)
btnPlay.Image = _startPlayIcon;
statusLabel.Text = "Playback finished.";
});
};
_waveOut.Play();
if (_stopPlayIcon != null)
btnPlay.Image = _stopPlayIcon;
statusLabel.Text = "Playing...";
}
}
catch (Exception ex)
{
MessageBox.Show($"Error playing audio: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private async void btnCall_Click(object sender, EventArgs e)
{
if (!_isCallActive)
{
btnCall.Enabled = false;
await StartCallAsync();
btnCall.Enabled = true;
}
else
{
await EndCallAsync();
}
}
private LogLevel GetSelectedLogLevel()
{
int selectedIndex = 6;
if (cmbLogLevel.InvokeRequired)
{
selectedIndex = (int)cmbLogLevel.Invoke(new Func<int>(() => cmbLogLevel.SelectedIndex));
}
else
{
selectedIndex = cmbLogLevel.SelectedIndex;
}
return selectedIndex switch
{
0 => LogLevel.Trace,
1 => LogLevel.Debug,
2 => LogLevel.Information,
3 => LogLevel.Warning,
4 => LogLevel.Error,
5 => LogLevel.Critical,
6 => LogLevel.None,
_ => LogLevel.None
};
}
private async Task StartCallAsync()
{
try
{
var config = new ConfigurationBuilder().AddUserSecrets<MainForm>().Build();
bool isGemini = cmbProvider.SelectedIndex == 1;
bool isBedrock = cmbProvider.SelectedIndex == 2;
bool isVertexAI = cmbProvider.SelectedIndex == 3;
if (isBedrock)
{
// AWS Bedrock: Authenticated via explicit IAM credentials (access key + secret key)
// stored in user secrets and passed as BasicAWSCredentials.
string? accessKeyId = config["AWS:AccessKeyId"];
string? secretAccessKey = config["AWS:SecretAccessKey"];
if (string.IsNullOrEmpty(accessKeyId) || string.IsNullOrEmpty(secretAccessKey))
{
WriteErrorToRichTextBox("AWS IAM credentials are not set. Use:\n" +
" dotnet user-secrets set \"AWS:AccessKeyId\" \"AKIA...\"\n" +
" dotnet user-secrets set \"AWS:SecretAccessKey\" \"<your-secret-key>\"");
return;
}
var regionName = config["AWS:Region"] ?? "us-east-1";
var credentials = new Amazon.Runtime.BasicAWSCredentials(accessKeyId, secretAccessKey);
var bedrockConfig = new Amazon.BedrockRuntime.AmazonBedrockRuntimeConfig
{
RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName(regionName),
Timeout = TimeSpan.FromMinutes(10)
};
_realtimeClient = new BedrockNovaRealtimeClient(
new Amazon.BedrockRuntime.AmazonBedrockRuntimeClient(credentials, bedrockConfig),
"amazon.nova-2-sonic-v1:0");
}
else if (isGemini)
{
// Google Gemini (AI Studio): Authenticated via a plain API key
// obtained from Google AI Studio and stored in user secrets.
string? geminiKey = config["Google:AI:ApiKey"];
if (string.IsNullOrEmpty(geminiKey))
{
WriteErrorToRichTextBox("Gemini API key is not set. Use: dotnet user-secrets set \"GeminiApiKey\" \"<key>\"");
return;
}
_realtimeClient = new GoogleGenAIRealtimeClient(geminiKey, "gemini-3.1-flash-live-preview");
}
else if (isVertexAI)
{
// Vertex AI: Authenticated via a service account JSON stored in user secrets,
// or falls back to Application Default Credentials (ADC) if not set.
// To use a service account:
// $json = Get-Content service-account.json -Raw
// dotnet user-secrets set "Google:Cloud:ServiceAccountJson" $json
// To use ADC instead: gcloud auth application-default login
string? serviceAccountJson = config["Google:Cloud:ServiceAccountJson"];
string? projectId = config["Google:Cloud:ProjectId"];
string? location = config["Google:Cloud:Location"] ?? "us-central1";
// Extract project_id from the service account JSON if not explicitly set
if (string.IsNullOrEmpty(projectId) && !string.IsNullOrEmpty(serviceAccountJson))
{
try
{
using var doc = System.Text.Json.JsonDocument.Parse(serviceAccountJson);
projectId = doc.RootElement.TryGetProperty("project_id", out var pid) ? pid.GetString() : null;
}
catch (System.Text.Json.JsonException)
{
// Invalid JSON — will fail below
}
}
if (string.IsNullOrEmpty(projectId))
{
WriteErrorToRichTextBox("Google Cloud project ID is not set. Either set Google:Cloud:ServiceAccountJson (which contains project_id) or set Google:Cloud:ProjectId explicitly.");
return;
}
string vertexModel = $"projects/{projectId}/locations/{location}/publishers/google/models/gemini-live-2.5-flash-native-audio";
var vertexBuilder = new PredictionServiceClientBuilder
{
Endpoint = $"{location}-aiplatform.googleapis.com",
};
if (!string.IsNullOrEmpty(serviceAccountJson))
{
vertexBuilder.JsonCredentials = serviceAccountJson;
}
_realtimeClient = vertexBuilder.BuildIRealtimeClient(vertexModel);
}
else
{
// OpenAI: Authenticated via an API key from the OpenAI platform,
// stored in user secrets and passed directly to the client constructor.
string? openAiKey = config["OpenAIKey"];
if (string.IsNullOrEmpty(openAiKey))
{
WriteErrorToRichTextBox("OpenAI API key is not set. Use: dotnet user-secrets set \"OpenAIKey\" \"<key>\"");
return;
}
_realtimeClient = new OpenAIRealtimeClient(openAiKey, "gpt-realtime-1.5");
}
string providerName = isBedrock ? "AWS Bedrock" : isGemini ? "Google Gemini" : isVertexAI ? "Vertex AI" : "OpenAI";
statusLabel.Text = $"Connecting to {providerName}...";
AIFunction getWeatherFunction = AIFunctionFactory.Create(
(string location) =>
location.ToLowerInvariant() switch
{
var l when l.Contains("seattle") => $"The weather in {location} is rainy, 55°F",
var l when l.Contains("new york") => $"The weather in {location} is cloudy, 70°F",
var l when l.Contains("san francisco") => $"The weather in {location} is foggy, 60°F",
_ => $"Sorry, I don't have weather data for {location}."
},
"GetWeather",
"Gets the current weather for a given location");
string selectedVoice = cmbVoice.SelectedItem?.ToString() ?? (isBedrock ? "matthew" : (isGemini || isVertexAI) ? "Puck" : "alloy");
// Build session options (some fields are provider-specific)
RealtimeSessionOptions sessionOptions;
if (isBedrock)
{
sessionOptions = new RealtimeSessionOptions
{
Instructions = "You are a funny chat bot.",
Voice = selectedVoice,
MaxOutputTokens = 1024,
Tools = [getWeatherFunction],
InputAudioFormat = new RealtimeAudioFormat("audio/lpcm", 16000),
OutputAudioFormat = new RealtimeAudioFormat("audio/lpcm", 24000),
};