|
| 1 | +using System.Runtime.Versioning; |
| 2 | +using Android; |
| 3 | +using Android.Content; |
| 4 | +using Android.Content.PM; |
| 5 | +using Android.Media; |
| 6 | +using Android.OS; |
| 7 | +using AndroidX.Core.Content; |
| 8 | +using HuiYi.Audio; |
| 9 | +using HuiYi.Localization; |
| 10 | +using HuiYi.Speech; |
| 11 | + |
| 12 | +namespace HuiYi.App.Platform; |
| 13 | + |
| 14 | +/// Captures 16 kHz mono PCM16 microphone audio on a dedicated thread and reports system silence |
| 15 | +/// transitions (API 29+ AudioRecordingCallback.IsClientSilenced). |
| 16 | +public sealed class AndroidMicSource : IAudioSource |
| 17 | +{ |
| 18 | + private const int SampleRate = Recognizer.SampleRate; |
| 19 | + private const int ChunkSamples = SampleRate / 10; // 1600 samples = 100 ms |
| 20 | + private const int BytesPerSample = sizeof(short); |
| 21 | + |
| 22 | + public event Action<float[]>? Samples; |
| 23 | + public event Action<string>? Failed; |
| 24 | + public event Action<bool>? SilencedChanged; |
| 25 | + |
| 26 | + private readonly Context appContext; |
| 27 | + private readonly object stateGate = new(); |
| 28 | + private readonly object lifecycleGate = new(); |
| 29 | + |
| 30 | + private AudioRecord? record; |
| 31 | + private AudioManager? audioManager; |
| 32 | + private AudioManager.AudioRecordingCallback? recordingCallback; |
| 33 | + private Thread? captureThread; |
| 34 | + private volatile bool running; |
| 35 | + private volatile bool disposed; |
| 36 | + private bool lastSilenced; |
| 37 | + |
| 38 | + public AndroidMicSource(Context? context = null) |
| 39 | + { |
| 40 | + appContext = context?.ApplicationContext |
| 41 | + ?? context |
| 42 | + ?? global::Android.App.Application.Context; |
| 43 | + } |
| 44 | + |
| 45 | + public void Start() |
| 46 | + { |
| 47 | + lock (lifecycleGate) |
| 48 | + { |
| 49 | + ObjectDisposedException.ThrowIf(disposed, this); |
| 50 | + if (running) return; |
| 51 | + |
| 52 | + if (ContextCompat.CheckSelfPermission(appContext, Manifest.Permission.RecordAudio) != Permission.Granted) |
| 53 | + { |
| 54 | + Log.Debug("mic: RECORD_AUDIO permission not granted"); |
| 55 | + Failed?.Invoke(L.T("无法打开麦克风:") + "RECORD_AUDIO permission not granted"); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + var minBuf = AudioRecord.GetMinBufferSize( |
| 60 | + SampleRate, |
| 61 | + ChannelIn.Mono, |
| 62 | + global::Android.Media.Encoding.Pcm16bit); |
| 63 | + var bufferBytes = Math.Max(minBuf * 2, ChunkSamples * BytesPerSample * 4); |
| 64 | + |
| 65 | + var created = TryCreateAudioRecord(AudioSource.VoiceRecognition, bufferBytes) |
| 66 | + ?? TryCreateAudioRecord(AudioSource.Mic, bufferBytes); |
| 67 | + |
| 68 | + if (created == null) |
| 69 | + { |
| 70 | + Failed?.Invoke(L.T("无法打开麦克风:") + "AudioRecord initialization failed"); |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + try |
| 75 | + { |
| 76 | + created.StartRecording(); |
| 77 | + if (created.RecordingState != RecordState.Recording) |
| 78 | + { |
| 79 | + throw new InvalidOperationException($"Unexpected AudioRecord state: {created.RecordingState}"); |
| 80 | + } |
| 81 | + } |
| 82 | + catch (Exception e) |
| 83 | + { |
| 84 | + Log.Debug($"mic: StartRecording failed ({e.GetType().Name}: {e.Message})"); |
| 85 | + ReleaseAudioRecord(created); |
| 86 | + Failed?.Invoke(L.T("无法打开麦克风:") + e.Message); |
| 87 | + return; |
| 88 | + } |
| 89 | + |
| 90 | + var sessionId = created.AudioSessionId; |
| 91 | + AudioManager? am = null; |
| 92 | + AudioManager.AudioRecordingCallback? cb = null; |
| 93 | + if (OperatingSystem.IsAndroidVersionAtLeast(29)) |
| 94 | + { |
| 95 | + am = appContext.GetSystemService(Context.AudioService) as AudioManager; |
| 96 | + if (am != null) |
| 97 | + { |
| 98 | + cb = new RecordingCallback(this, sessionId); |
| 99 | + am.RegisterAudioRecordingCallback(cb, new Handler(Looper.MainLooper!)); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + lock (stateGate) |
| 104 | + { |
| 105 | + record = created; |
| 106 | + audioManager = am; |
| 107 | + recordingCallback = cb; |
| 108 | + lastSilenced = false; |
| 109 | + running = true; |
| 110 | + } |
| 111 | + |
| 112 | + if (OperatingSystem.IsAndroidVersionAtLeast(29) && am != null) |
| 113 | + { |
| 114 | + UpdateSilencedFromConfigs(am.ActiveRecordingConfigurations, sessionId); |
| 115 | + } |
| 116 | + |
| 117 | + var thread = new Thread(() => CaptureLoop(created)) |
| 118 | + { |
| 119 | + IsBackground = true, |
| 120 | + Name = "huiyi-mic", |
| 121 | + Priority = System.Threading.ThreadPriority.AboveNormal |
| 122 | + }; |
| 123 | + lock (stateGate) |
| 124 | + { |
| 125 | + captureThread = thread; |
| 126 | + } |
| 127 | + thread.Start(); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + public void Stop() => StopCore(disposing: false); |
| 132 | + |
| 133 | + public void Dispose() |
| 134 | + { |
| 135 | + disposed = true; |
| 136 | + StopCore(disposing: true); |
| 137 | + } |
| 138 | + |
| 139 | + private void StopCore(bool disposing) |
| 140 | + { |
| 141 | + AudioRecord? rec; |
| 142 | + AudioManager? am; |
| 143 | + AudioManager.AudioRecordingCallback? cb; |
| 144 | + Thread? thread; |
| 145 | + bool wasSilenced; |
| 146 | + |
| 147 | + lock (lifecycleGate) |
| 148 | + { |
| 149 | + lock (stateGate) |
| 150 | + { |
| 151 | + if (!running && record == null && recordingCallback == null && captureThread == null) |
| 152 | + { |
| 153 | + return; |
| 154 | + } |
| 155 | + |
| 156 | + running = false; |
| 157 | + rec = record; |
| 158 | + record = null; |
| 159 | + am = audioManager; |
| 160 | + audioManager = null; |
| 161 | + cb = recordingCallback; |
| 162 | + recordingCallback = null; |
| 163 | + thread = captureThread; |
| 164 | + captureThread = null; |
| 165 | + wasSilenced = lastSilenced; |
| 166 | + lastSilenced = false; |
| 167 | + } |
| 168 | + |
| 169 | + if (OperatingSystem.IsAndroidVersionAtLeast(29) && am != null && cb != null) |
| 170 | + { |
| 171 | + try { am.UnregisterAudioRecordingCallback(cb); } catch { } |
| 172 | + try { cb.Dispose(); } catch { } |
| 173 | + } |
| 174 | + |
| 175 | + if (rec != null) |
| 176 | + { |
| 177 | + try { rec.Stop(); } catch { } |
| 178 | + } |
| 179 | + |
| 180 | + if (thread != null && thread != Thread.CurrentThread) |
| 181 | + { |
| 182 | + try { thread.Join(2000); } catch { } |
| 183 | + } |
| 184 | + |
| 185 | + if (rec != null) |
| 186 | + { |
| 187 | + ReleaseAudioRecord(rec); |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + if (wasSilenced && !disposing) |
| 192 | + { |
| 193 | + SilencedChanged?.Invoke(false); |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + private static AudioRecord? TryCreateAudioRecord(AudioSource source, int bufferBytes) |
| 198 | + { |
| 199 | + AudioRecord? candidate = null; |
| 200 | + try |
| 201 | + { |
| 202 | + candidate = new AudioRecord( |
| 203 | + source, |
| 204 | + SampleRate, |
| 205 | + ChannelIn.Mono, |
| 206 | + global::Android.Media.Encoding.Pcm16bit, |
| 207 | + bufferBytes); |
| 208 | + |
| 209 | + if (candidate.State == global::Android.Media.State.Initialized) |
| 210 | + { |
| 211 | + Log.Debug($"mic: initialized {source} at {SampleRate} Hz (buffer {bufferBytes} B)"); |
| 212 | + return candidate; |
| 213 | + } |
| 214 | + |
| 215 | + Log.Debug($"mic: {source} init state={candidate.State}"); |
| 216 | + } |
| 217 | + catch (Exception e) |
| 218 | + { |
| 219 | + Log.Debug($"mic: {source} init failed ({e.GetType().Name}: {e.Message})"); |
| 220 | + } |
| 221 | + |
| 222 | + ReleaseAudioRecord(candidate); |
| 223 | + return null; |
| 224 | + } |
| 225 | + |
| 226 | + private static void ReleaseAudioRecord(AudioRecord? rec) |
| 227 | + { |
| 228 | + if (rec == null) return; |
| 229 | + try { rec.Release(); } catch { } |
| 230 | + try { rec.Dispose(); } catch { } |
| 231 | + } |
| 232 | + |
| 233 | + private void CaptureLoop(AudioRecord rec) |
| 234 | + { |
| 235 | + try |
| 236 | + { |
| 237 | + global::Android.OS.Process.SetThreadPriority(global::Android.OS.ThreadPriority.Audio); |
| 238 | + } |
| 239 | + catch |
| 240 | + { |
| 241 | + // Continue with managed AboveNormal priority if OS rejects native audio priority. |
| 242 | + } |
| 243 | + |
| 244 | + var pcm = new short[ChunkSamples]; |
| 245 | + var offset = 0; |
| 246 | + |
| 247 | + while (running) |
| 248 | + { |
| 249 | + int read; |
| 250 | + try |
| 251 | + { |
| 252 | + read = rec.Read(pcm, offset, ChunkSamples - offset); |
| 253 | + } |
| 254 | + catch (Exception e) |
| 255 | + { |
| 256 | + if (!running) break; |
| 257 | + Log.Debug($"mic: read exception ({e.GetType().Name}: {e.Message})"); |
| 258 | + Failed?.Invoke(L.T("无法打开麦克风:") + e.Message); |
| 259 | + break; |
| 260 | + } |
| 261 | + |
| 262 | + if (!running) break; |
| 263 | + |
| 264 | + if (read > 0) |
| 265 | + { |
| 266 | + offset += read; |
| 267 | + if (offset < ChunkSamples) continue; |
| 268 | + |
| 269 | + var samples = new float[ChunkSamples]; |
| 270 | + for (var i = 0; i < ChunkSamples; i++) |
| 271 | + { |
| 272 | + samples[i] = pcm[i] / 32768f; |
| 273 | + } |
| 274 | + offset = 0; |
| 275 | + Samples?.Invoke(samples); |
| 276 | + } |
| 277 | + else if (read == 0) |
| 278 | + { |
| 279 | + Thread.Sleep(5); |
| 280 | + } |
| 281 | + else |
| 282 | + { |
| 283 | + if (!running) break; |
| 284 | + Log.Debug($"mic: read failed ({read})"); |
| 285 | + Failed?.Invoke(L.T("无法打开麦克风:") + $"AudioRecord error {read}"); |
| 286 | + break; |
| 287 | + } |
| 288 | + } |
| 289 | + } |
| 290 | + |
| 291 | + [SupportedOSPlatform("android29.0")] |
| 292 | + private void UpdateSilencedFromConfigs(IList<AudioRecordingConfiguration>? configs, int sessionId) |
| 293 | + { |
| 294 | + if (!running || disposed || configs == null) return; |
| 295 | + |
| 296 | + AudioRecordingConfiguration? mine = null; |
| 297 | + foreach (var cfg in configs) |
| 298 | + { |
| 299 | + if (cfg != null && cfg.ClientAudioSessionId == sessionId) |
| 300 | + { |
| 301 | + mine = cfg; |
| 302 | + break; |
| 303 | + } |
| 304 | + } |
| 305 | + |
| 306 | + if (mine == null) return; |
| 307 | + |
| 308 | + var silenced = mine.IsClientSilenced; |
| 309 | + lock (stateGate) |
| 310 | + { |
| 311 | + if (!running || disposed || lastSilenced == silenced) return; |
| 312 | + lastSilenced = silenced; |
| 313 | + } |
| 314 | + |
| 315 | + Log.Debug($"mic: silenced={silenced}"); |
| 316 | + SilencedChanged?.Invoke(silenced); |
| 317 | + } |
| 318 | + |
| 319 | + [SupportedOSPlatform("android29.0")] |
| 320 | + private sealed class RecordingCallback(AndroidMicSource owner, int sessionId) |
| 321 | + : AudioManager.AudioRecordingCallback |
| 322 | + { |
| 323 | + public override void OnRecordingConfigChanged(IList<AudioRecordingConfiguration>? configs) |
| 324 | + { |
| 325 | + base.OnRecordingConfigChanged(configs); |
| 326 | + owner.UpdateSilencedFromConfigs(configs, sessionId); |
| 327 | + } |
| 328 | + } |
| 329 | +} |
0 commit comments