|
| 1 | +using AIStudio.Tools.MIME; |
| 2 | +using AIStudio.Tools.Services; |
| 3 | + |
| 4 | +using Microsoft.AspNetCore.Components; |
| 5 | + |
| 6 | +namespace AIStudio.Components; |
| 7 | + |
| 8 | +public partial class VoiceRecorder : MSGComponentBase |
| 9 | +{ |
| 10 | + [Inject] |
| 11 | + private ILogger<VoiceRecorder> Logger { get; init; } = null!; |
| 12 | + |
| 13 | + [Inject] |
| 14 | + private IJSRuntime JsRuntime { get; init; } = null!; |
| 15 | + |
| 16 | + [Inject] |
| 17 | + private RustService RustService { get; init; } = null!; |
| 18 | + |
| 19 | + private uint numReceivedChunks; |
| 20 | + private bool isRecording; |
| 21 | + private FileStream? currentRecordingStream; |
| 22 | + private string? currentRecordingPath; |
| 23 | + private string? currentRecordingMimeType; |
| 24 | + private DotNetObjectReference<VoiceRecorder>? dotNetReference; |
| 25 | + |
| 26 | + private string Tooltip => this.isRecording ? T("Stop recording and start transcription") : T("Start recording your voice for a transcription"); |
| 27 | + |
| 28 | + private async Task OnRecordingToggled(bool toggled) |
| 29 | + { |
| 30 | + if (toggled) |
| 31 | + { |
| 32 | + var mimeTypes = GetPreferredMimeTypes( |
| 33 | + Builder.Create().UseAudio().UseSubtype(AudioSubtype.OGG).Build(), |
| 34 | + Builder.Create().UseAudio().UseSubtype(AudioSubtype.AAC).Build(), |
| 35 | + Builder.Create().UseAudio().UseSubtype(AudioSubtype.MP3).Build(), |
| 36 | + Builder.Create().UseAudio().UseSubtype(AudioSubtype.AIFF).Build(), |
| 37 | + Builder.Create().UseAudio().UseSubtype(AudioSubtype.WAV).Build(), |
| 38 | + Builder.Create().UseAudio().UseSubtype(AudioSubtype.FLAC).Build() |
| 39 | + ); |
| 40 | + |
| 41 | + this.Logger.LogInformation("Starting audio recording with preferred MIME types: '{PreferredMimeTypes}'.", string.Join<MIMEType>(", ", mimeTypes)); |
| 42 | + |
| 43 | + // Create a DotNetObjectReference to pass to JavaScript: |
| 44 | + this.dotNetReference = DotNetObjectReference.Create(this); |
| 45 | + |
| 46 | + // Initialize the file stream for writing chunks: |
| 47 | + await this.InitializeRecordingStream(); |
| 48 | + |
| 49 | + var mimeTypeStrings = mimeTypes.ToStringArray(); |
| 50 | + var actualMimeType = await this.JsRuntime.InvokeAsync<string>("audioRecorder.start", this.dotNetReference, mimeTypeStrings); |
| 51 | + |
| 52 | + // Store the MIME type for later use: |
| 53 | + this.currentRecordingMimeType = actualMimeType; |
| 54 | + |
| 55 | + this.Logger.LogInformation("Audio recording started with MIME type: '{ActualMimeType}'.", actualMimeType); |
| 56 | + this.isRecording = true; |
| 57 | + } |
| 58 | + else |
| 59 | + { |
| 60 | + var result = await this.JsRuntime.InvokeAsync<AudioRecordingResult>("audioRecorder.stop"); |
| 61 | + if (result.ChangedMimeType) |
| 62 | + this.Logger.LogWarning("The recorded audio MIME type was changed to '{ResultMimeType}'.", result.MimeType); |
| 63 | + |
| 64 | + // Close and finalize the recording stream: |
| 65 | + await this.FinalizeRecordingStream(); |
| 66 | + |
| 67 | + this.isRecording = false; |
| 68 | + this.StateHasChanged(); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + private static MIMEType[] GetPreferredMimeTypes(params MIMEType[] mimeTypes) |
| 73 | + { |
| 74 | + // Default list if no parameters provided: |
| 75 | + if (mimeTypes.Length is 0) |
| 76 | + { |
| 77 | + var audioBuilder = Builder.Create().UseAudio(); |
| 78 | + return |
| 79 | + [ |
| 80 | + audioBuilder.UseSubtype(AudioSubtype.WEBM).Build(), |
| 81 | + audioBuilder.UseSubtype(AudioSubtype.OGG).Build(), |
| 82 | + audioBuilder.UseSubtype(AudioSubtype.MP4).Build(), |
| 83 | + audioBuilder.UseSubtype(AudioSubtype.MPEG).Build(), |
| 84 | + ]; |
| 85 | + } |
| 86 | + |
| 87 | + return mimeTypes; |
| 88 | + } |
| 89 | + |
| 90 | + private async Task InitializeRecordingStream() |
| 91 | + { |
| 92 | + this.numReceivedChunks = 0; |
| 93 | + var dataDirectory = await this.RustService.GetDataDirectory(); |
| 94 | + var recordingDirectory = Path.Combine(dataDirectory, "audioRecordings"); |
| 95 | + if (!Directory.Exists(recordingDirectory)) |
| 96 | + Directory.CreateDirectory(recordingDirectory); |
| 97 | + |
| 98 | + var fileName = $"recording_{DateTime.UtcNow:yyyyMMdd_HHmmss}.audio"; |
| 99 | + this.currentRecordingPath = Path.Combine(recordingDirectory, fileName); |
| 100 | + this.currentRecordingStream = new FileStream(this.currentRecordingPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 8192, useAsync: true); |
| 101 | + |
| 102 | + this.Logger.LogInformation("Initialized audio recording stream: '{RecordingPath}'.", this.currentRecordingPath); |
| 103 | + } |
| 104 | + |
| 105 | + [JSInvokable] |
| 106 | + public async Task OnAudioChunkReceived(byte[] chunkBytes) |
| 107 | + { |
| 108 | + if (this.currentRecordingStream is null) |
| 109 | + { |
| 110 | + this.Logger.LogWarning("Received audio chunk but no recording stream is active."); |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + try |
| 115 | + { |
| 116 | + this.numReceivedChunks++; |
| 117 | + await this.currentRecordingStream.WriteAsync(chunkBytes); |
| 118 | + await this.currentRecordingStream.FlushAsync(); |
| 119 | + |
| 120 | + this.Logger.LogDebug("Wrote {ByteCount} bytes to recording stream.", chunkBytes.Length); |
| 121 | + } |
| 122 | + catch (Exception ex) |
| 123 | + { |
| 124 | + this.Logger.LogError(ex, "Error writing audio chunk to stream."); |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + private async Task FinalizeRecordingStream() |
| 129 | + { |
| 130 | + if (this.currentRecordingStream is not null) |
| 131 | + { |
| 132 | + await this.currentRecordingStream.FlushAsync(); |
| 133 | + await this.currentRecordingStream.DisposeAsync(); |
| 134 | + this.currentRecordingStream = null; |
| 135 | + |
| 136 | + // Rename the file with the correct extension based on MIME type: |
| 137 | + if (this.currentRecordingPath is not null && this.currentRecordingMimeType is not null) |
| 138 | + { |
| 139 | + var extension = GetFileExtension(this.currentRecordingMimeType); |
| 140 | + var newPath = Path.ChangeExtension(this.currentRecordingPath, extension); |
| 141 | + |
| 142 | + if (File.Exists(this.currentRecordingPath)) |
| 143 | + { |
| 144 | + File.Move(this.currentRecordingPath, newPath, overwrite: true); |
| 145 | + this.Logger.LogInformation("Finalized audio recording over {NumChunks} streamed audio chunks to the file '{RecordingPath}'.", this.numReceivedChunks, newPath); |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + this.currentRecordingPath = null; |
| 151 | + this.currentRecordingMimeType = null; |
| 152 | + |
| 153 | + // Dispose the .NET reference: |
| 154 | + this.dotNetReference?.Dispose(); |
| 155 | + this.dotNetReference = null; |
| 156 | + } |
| 157 | + |
| 158 | + private static string GetFileExtension(string mimeType) |
| 159 | + { |
| 160 | + var baseMimeType = mimeType.Split(';')[0].Trim().ToLowerInvariant(); |
| 161 | + return baseMimeType switch |
| 162 | + { |
| 163 | + "audio/webm" => ".webm", |
| 164 | + "audio/ogg" => ".ogg", |
| 165 | + "audio/mp4" => ".m4a", |
| 166 | + "audio/mpeg" => ".mp3", |
| 167 | + "audio/wav" => ".wav", |
| 168 | + "audio/x-wav" => ".wav", |
| 169 | + _ => ".audio" // Fallback |
| 170 | + }; |
| 171 | + } |
| 172 | + |
| 173 | + private sealed class AudioRecordingResult |
| 174 | + { |
| 175 | + public string MimeType { get; init; } = string.Empty; |
| 176 | + |
| 177 | + public bool ChangedMimeType { get; init; } |
| 178 | + } |
| 179 | + |
| 180 | + #region Overrides of MSGComponentBase |
| 181 | + |
| 182 | + protected override void DisposeResources() |
| 183 | + { |
| 184 | + // Clean up recording resources if still active: |
| 185 | + if (this.currentRecordingStream is not null) |
| 186 | + { |
| 187 | + this.currentRecordingStream.Dispose(); |
| 188 | + this.currentRecordingStream = null; |
| 189 | + } |
| 190 | + |
| 191 | + this.dotNetReference?.Dispose(); |
| 192 | + this.dotNetReference = null; |
| 193 | + base.DisposeResources(); |
| 194 | + } |
| 195 | + |
| 196 | + #endregion |
| 197 | +} |
0 commit comments