Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add mobile external microphone selection
cybersader019a67fb8670
diff --git a/docs/assets/images/screenshots/recording-external-microphone-mobile.png b/docs/assets/images/screenshots/recording-external-microphone-mobile.pngnew file mode 100644index 00000000..9f2e56e3Binary files /dev/null and b/docs/assets/images/screenshots/recording-external-microphone-mobile.png differdiff --git a/docs/user-guide/recording.md b/docs/user-guide/recording.mdindex 1360ad24..b41e20a8 100644--- a/docs/user-guide/recording.md+++ b/docs/user-guide/recording.md@@ -131,12 +131,20 @@ Under the recording buttons is a collapsible **Input devices** section. Expanded-- **Primary input** — defaults to your OS's default microphone. Pick a specific input here if you want a USB headset, BlackHole, VB-Cable, or a Pulse / PipeWire monitor source as your primary capture device. Virtual / monitor entries are badged.+- **Primary input** — defaults to your OS's default microphone. Pick a specific input here if you want a USB headset, wireless receiver, audio interface, BlackHole, VB-Cable, or a Pulse / PipeWire monitor source as your primary capture device. Virtual / monitor entries are badged. The primary selection is used by both **Microphone** and **Mic + System** recording.- **Also mix in (optional)** — pick a second input device and Speakr will capture both streams in parallel and mix them via Web Audio into one MediaRecorder track. This is the canonical solution for **capturing both sides of a meeting** on macOS or Linux where the browser can't capture full system audio natively — set your real mic as Primary, set BlackHole / `speakr_loopback` / VB-Cable as the secondary, and one recording captures your voice plus the remote participants.-Device labels are blank until you grant microphone permission. The first time you expand the picker, click the **Request microphone permission** link so the OS shows the prompt; subsequent recordings remember the permission and the labels populate.+Opening **New Recording** does not request microphone permission. Device labels are normally blank until permission is granted. You can expand the picker and click **Request microphone permission**, or simply press **Microphone** and respond to the browser's normal permission prompt.-**Persistence**: the primary + secondary device choices are saved in `localStorage` so you configure them once and they survive across sessions.+On mobile, after permission is granted, Speakr checks the labeled inputs. If a likely separate physical microphone is available and you have not already selected one, the existing **Input devices** section expands with an **Another microphone is available** notice before recording starts. Choose the input and continue, or keep the system default. When only the built-in/default microphone is present, recording starts immediately with no extra Speakr prompt. Because browsers do not reliably expose connection type, the detection covers likely USB receivers, wireless/headset microphones, webcams, and audio interfaces rather than claiming that a device is definitely USB.++++Desktop browsers already provide their own microphone chooser, so Speakr does not automatically open a second selection step there. The collapsed **Input devices** picker remains available for an explicit device choice or multi-input mixing, and any microphone chosen in the browser's permission dialog remains active unless you deliberately override it in Speakr.++Automatic mobile detection is deliberately conservative. If your browser hides labels or grouping metadata, open **Input devices** and select the device manually. Speakr refreshes the list when the browser reports a device change and again when recording starts. A previously selected device that has been disconnected falls back to the system default with a warning.++**Persistence**: the primary + secondary device choices are saved in `localStorage` so you configure them once and they survive across sessions. Choosing to keep the default when Speakr offers another microphone is remembered only for the current browser session and is reconsidered when the candidate device set changes.### Disable echo cancellation, noise suppression & auto-gain@@ -341,6 +349,8 @@ Because notes cannot be meaningfully combined, when more than one source has notSee the [PWA Guide](pwa.md) for installation instructions and important limitations.+**External microphones on Android:** Current Chromium-based browsers can expose class-compliant USB-C receivers and other external inputs through the normal microphone device list. Speakr can select only devices the browser exposes; it cannot force Android to route unsupported hardware. Device labels and `groupId` metadata vary by browser, `devicechange` may not fire on every phone, and device IDs can change after permissions or browser data are reset. If automatic detection does not appear, reconnect the receiver, grant microphone permission, and check **Input devices** manually. Verify the actual recorded source with a short test recording rather than relying only on the displayed device name.+### Optimizing Audio QualityThe quality of your transcription starts with the quality of your recording. When using a microphone, find a quiet space with minimal echo and background noise. Soft furnishings and carpeted rooms generally provide better acoustics than empty rooms with hard surfaces. Position your microphone consistently, about 6-12 inches from your mouth, and speak at a steady volume.diff --git a/static/js/app.modular.js b/static/js/app.modular.jsindex faa3d8a9..bcd53350 100644--- a/static/js/app.modular.js+++ b/static/js/app.modular.js@@ -1,4 +1,4 @@-const { createApp, ref, reactive, computed, onMounted, watch, nextTick } = Vue;+const { createApp, ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } = Vue;// Import composablesimport { useRecordings } from './modules/composables/recordings.js';@@ -22,7 +22,12 @@ import { useFolders } from './modules/composables/folders.js';import { showToast } from './modules/utils/toast.js';import { getContrastTextColor } from './modules/utils/colors.js';import { buildVariableList } from './modules/utils/prompt-variables.js';-import { detectPlatform, getAudioCapabilities, enumerateVirtualAudioDevices } from './modules/utils/platform.js';+import {+ detectPlatform,+ getAudioCapabilities,+ enumerateVirtualAudioDevices,+ normalizeAudioInputDevices+} from './modules/utils/platform.js';// Number of speaker colors available in CSS (must match styles.css)const SPEAKER_COLOR_COUNT = 16;@@ -436,19 +441,32 @@ document.addEventListener('DOMContentLoaded', async () => {try { localStorage.setItem('selectedSecondaryDeviceId', v || ''); } catch (_) {}});const refreshInputAudioDevices = async () => {- if (typeof navigator === 'undefined' || !navigator.mediaDevices) return;+ if (typeof navigator === 'undefined'+ || !navigator.mediaDevices+ || typeof navigator.mediaDevices.enumerateDevices !== 'function') {+ return [];+ }try {const devs = await navigator.mediaDevices.enumerateDevices();- inputAudioDevices.value = devs- .filter(d => d.kind === 'audioinput')- .map(d => ({- deviceId: d.deviceId,- label: d.label || '',- // Tag virtual/monitor devices so the UI can badge them- isVirtual: /\bmonitor of |blackhole|loopback|soundflower|vb[- ]?(audio|cable)|voicemeeter|stereo mix|what u hear|pulse.*monitor|pipewire.*monitor|monitor source/i.test(d.label || '')- }));+ const inputs = normalizeAudioInputDevices(devs);+ inputAudioDevices.value = inputs;++ // Before permission, browsers often expose only opaque or+ // blank entries. Reconcile persisted IDs only once labels+ // prove that the full device list is available.+ if (inputs.some(device => device.label)) {+ const availableIds = new Set(inputs.map(device => device.deviceId));+ if (selectedMicDeviceId.value && !availableIds.has(selectedMicDeviceId.value)) {+ selectedMicDeviceId.value = '';+ }+ if (selectedSecondaryDeviceId.value && !availableIds.has(selectedSecondaryDeviceId.value)) {+ selectedSecondaryDeviceId.value = '';+ }+ }+ return inputs;} catch (_) {inputAudioDevices.value = [];+ return [];}};refreshInputAudioDevices();@@ -475,6 +493,26 @@ document.addEventListener('DOMContentLoaded', async () => {// so the result is often []; refreshed again after the// first getUserMedia / getDisplayMedia grant.refreshVirtualAudioDevices();++ const handleAudioDeviceChange = () => {+ refreshInputAudioDevices();+ refreshVirtualAudioDevices();+ };+ onMounted(() => {+ if (typeof navigator !== 'undefined'+ && navigator.mediaDevices+ && typeof navigator.mediaDevices.addEventListener === 'function') {+ navigator.mediaDevices.addEventListener('devicechange', handleAudioDeviceChange);+ }+ });+ onUnmounted(() => {+ if (typeof navigator !== 'undefined'+ && navigator.mediaDevices+ && typeof navigator.mediaDevices.removeEventListener === 'function') {+ navigator.mediaDevices.removeEventListener('devicechange', handleAudioDeviceChange);+ }+ });+const showRecoveryModal = ref(false);const recoverableRecording = ref(null);const asrLanguage = ref('');diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.jsindex 138375d9..c2f79953 100644--- a/static/js/modules/composables/audio.js+++ b/static/js/modules/composables/audio.js@@ -6,6 +6,45 @@import * as RecordingDB from '../db/recording-persistence.js';import * as IncognitoStorage from '../db/incognito-storage.js';import * as ServerSessions from '../db/server-recording-sessions.js';+import {+ findExternalAudioInputCandidates,+ getAudioInputCandidateSignature,+ shouldAutoOfferExternalAudioInput+} from '../utils/platform.js';++export function buildMicrophoneConstraints(deviceId = '', disableAudioProcessing = false) {+ const constraints = {+ echoCancellation: !disableAudioProcessing,+ noiseSuppression: !disableAudioProcessing,+ autoGainControl: !disableAudioProcessing,+ sampleRate: 48000+ };+ if (deviceId) constraints.deviceId = { exact: deviceId };+ return constraints;+}++export function isUnavailableAudioInputError(error) {+ return error?.name === 'NotFoundError' || error?.name === 'OverconstrainedError';+}++export async function acquireMicrophoneStream(mediaDevices, options = {}) {+ const deviceId = options.deviceId || '';+ const disableAudioProcessing = !!options.disableAudioProcessing;++ try {+ const stream = await mediaDevices.getUserMedia({+ audio: buildMicrophoneConstraints(deviceId, disableAudioProcessing)+ });+ return { stream, requestedDeviceId: deviceId, usedFallback: false, originalError: null };+ } catch (error) {+ if (!deviceId || !isUnavailableAudioInputError(error)) throw error;++ const stream = await mediaDevices.getUserMedia({+ audio: buildMicrophoneConstraints('', disableAudioProcessing)+ });+ return { stream, requestedDeviceId: deviceId, usedFallback: true, originalError: error };+ }+}export function useAudio(state, utils) {const {@@ -15,7 +54,7 @@ export function useAudio(state, utils) {maxRecordingMB, fileSizeWarningShown, sizeCheckInterval, isServerStreamedRecording, isFinalizingRecording, recordingDisclaimer,showRecordingDisclaimerModal, pendingRecordingMode, currentView, showUploadModal, showSystemAudioHelp, disableAudioProcessing,recordSystemVideo, recordingVideoActive, videoRetentionEnabled,- selectedMicDeviceId, selectedSecondaryDeviceId,+ inputAudioDevices, selectedMicDeviceId, selectedSecondaryDeviceId,isDarkMode, wakeLock, animationFrameId,activeStreams, visualizer, micVisualizer, systemVisualizer, canRecordAudio,canRecordSystemAudio, systemAudioSupported, systemAudioError, globalError,@@ -39,6 +78,63 @@ export function useAudio(state, utils) {// estimate reflects the WHOLE recording, not just the new segment.let serverResumePriorBytes = 0;+ const isPreparingRecording = Vue.ref(false);+ const pendingMicrophoneSelection = Vue.ref(null);+ let pendingMicrophoneSelectionResolver = null;+ let dismissedMicrophoneCandidateSignature = '';+ const dismissedCandidateStorageKey = 'dismissedExternalMicCandidateSignature';++ try {+ dismissedMicrophoneCandidateSignature = sessionStorage.getItem(dismissedCandidateStorageKey) || '';+ } catch (_) { /* sessionStorage may be unavailable in private contexts */ }++ const rememberDismissedMicrophoneCandidates = (signature) => {+ dismissedMicrophoneCandidateSignature = signature || '';+ try {+ sessionStorage.setItem(dismissedCandidateStorageKey, dismissedMicrophoneCandidateSignature);+ } catch (_) { /* keep the in-memory fallback */ }+ };++ const waitForMicrophoneSelection = (candidates, activeDeviceId) => new Promise((resolve) => {+ const signature = getAudioInputCandidateSignature(candidates);+ pendingMicrophoneSelection.value = {+ candidates,+ activeDeviceId: activeDeviceId || '',+ candidateSignature: signature+ };+ pendingMicrophoneSelectionResolver = resolve;+ });++ const resolveMicrophoneSelection = (result) => {+ const resolver = pendingMicrophoneSelectionResolver;+ pendingMicrophoneSelectionResolver = null;+ pendingMicrophoneSelection.value = null;+ if (resolver) resolver(result);+ };++ const confirmPendingMicrophoneSelection = () => {+ const deviceId = (selectedMicDeviceId && selectedMicDeviceId.value) || '';+ const pending = pendingMicrophoneSelection.value;+ if (!deviceId && pending?.candidateSignature) {+ rememberDismissedMicrophoneCandidates(pending.candidateSignature);+ }+ resolveMicrophoneSelection(deviceId+ ? { action: 'select', deviceId }+ : { action: 'continue', deviceId: '' });+ };++ const cancelPendingMicrophoneSelection = () => {+ resolveMicrophoneSelection({ action: 'cancel', deviceId: '' });+ };++ if (typeof Vue !== 'undefined' && Vue.watch && showUploadModal) {+ Vue.watch(showUploadModal, (visible) => {+ if (!visible && pendingMicrophoneSelection.value) {+ cancelPendingMicrophoneSelection();+ }+ });+ }+// Phase B: server-side chunk streaming (#287 c/d). Feature-flagged via// the page-level dataset attribute `data-server-recording-chunks`// (rendered by Flask from ENABLE_SERVER_RECORDING_CHUNKS). When the@@ -314,61 +410,114 @@ export function useAudio(state, utils) {}};+ const refreshAudioDeviceLists = async () => {+ if (utils.refreshVirtualAudioDevices) utils.refreshVirtualAudioDevices();+ if (utils.refreshInputAudioDevices) return await utils.refreshInputAudioDevices();+ return (inputAudioDevices && inputAudioDevices.value) || [];+ };++ const showSelectedMicrophoneUnavailable = () => {+ const message = (utils.t && utils.t('recording.selectedMicUnavailable'))+ || 'The selected microphone is no longer available. Using the system default.';+ showToast(message, 'fa-exclamation-triangle');+ };++ const requestMicrophonePermission = async () => {+ if (!navigator.mediaDevices || typeof navigator.mediaDevices.getUserMedia !== 'function') {+ showToast(+ (utils.t && utils.t('recording.micPermissionUnavailable'))+ || 'Microphone access is not available. Make sure you are using HTTPS.',+ 'error'+ );+ return;+ }++ let permissionStream = null;+ try {+ permissionStream = await navigator.mediaDevices.getUserMedia({ audio: true });+ await refreshAudioDeviceLists();+ } catch (error) {+ const denied = error?.name === 'NotAllowedError' || error?.name === 'SecurityError';+ showToast(+ (utils.t && utils.t(denied ? 'recording.microphonePermissionDenied' : 'recording.micPermissionFailed'))+ || (denied+ ? 'Microphone permission was denied. Allow access in your browser settings and try again.'+ : 'Could not access the microphone. Check that it is connected and not in use.'),+ 'error'+ );+ } finally {+ if (permissionStream) permissionStream.getTracks().forEach(track => track.stop());+ }+ };+// Start recording// IMPORTANT: For Firefox, getDisplayMedia MUST be the first async call from user gestureconst startRecording = async (mode = 'microphone', resumeContext = null) => {- const needsDisplayMedia = mode === 'system' || mode === 'both';+ if (isPreparingRecording.value || isRecording.value) return;+ isPreparingRecording.value = true;- // For system audio modes, get display media FIRST before any other operations- // This is required for Firefox's "transient activation" security model- if (needsDisplayMedia) {- try {- const displayStream = await navigator.mediaDevices.getDisplayMedia({- video: true,- audio: true- });+ try {+ const needsDisplayMedia = mode === 'system' || mode === 'both';- // Check if we got an audio track- const audioTrack = displayStream.getAudioTracks()[0];- if (!audioTrack) {- displayStream.getTracks().forEach(track => track.stop());- // Open the platform-aware help modal so the user- // gets per-OS guidance instead of a bare toast.- if (showSystemAudioHelp) showSystemAudioHelp.value = true;- showToast('No audio track came through — see the help guide for per-OS setup.', 'fa-exclamation-triangle');+ // For system audio modes, get display media FIRST before any other operations+ // This is required for Firefox's "transient activation" security model+ if (needsDisplayMedia) {+ try {+ const displayStream = await navigator.mediaDevices.getDisplayMedia({+ video: true,+ audio: true+ });++ // Check if we got an audio track+ const audioTrack = displayStream.getAudioTracks()[0];+ if (!audioTrack) {+ displayStream.getTracks().forEach(track => track.stop());+ // Open the platform-aware help modal so the user+ // gets per-OS guidance instead of a bare toast.+ if (showSystemAudioHelp) showSystemAudioHelp.value = true;+ showToast('No audio track came through — see the help guide for per-OS setup.', 'fa-exclamation-triangle');+ return;+ }++ // Store stream for use after disclaimer (if any)+ pendingDisplayStream = displayStream;+ } catch (error) {+ console.error('[Recording] Failed to get display media:', error);+ if (error.name === 'NotAllowedError') {+ showToast('Screen sharing was cancelled', 'error');+ } else {+ showToast(`Failed to capture: ${error.message}`, 'error');+ }return;}+ }- // Store stream for use after disclaimer (if any)- pendingDisplayStream = displayStream;- } catch (error) {- console.error('[Recording] Failed to get display media:', error);- if (error.name === 'NotAllowedError') {- showToast('Screen sharing was cancelled', 'error');- } else {- showToast(`Failed to capture: ${error.message}`, 'error');- }+ // Now check for disclaimer (after we've secured the display stream)+ if (recordingDisclaimer.value && recordingDisclaimer.value.trim() !== '') {+ showRecordingDisclaimerModal.value = true;+ pendingRecordingMode.value = mode;+ pendingResumeContext = resumeContext;return;}- }- // Now check for disclaimer (after we've secured the display stream)- if (recordingDisclaimer.value && recordingDisclaimer.value.trim() !== '') {- showRecordingDisclaimerModal.value = true;- pendingRecordingMode.value = mode;- pendingResumeContext = resumeContext;- return;+ await startRecordingInternal(mode, resumeContext);+ } finally {+ isPreparingRecording.value = false;}-- await startRecordingInternal(mode, resumeContext);};// Accept recording disclaimer and start recordingconst acceptRecordingDisclaimer = async () => {+ if (isPreparingRecording.value || isRecording.value) return;+ isPreparingRecording.value = true;showRecordingDisclaimerModal.value = false;const resumeContext = pendingResumeContext;pendingResumeContext = null;- await startRecordingInternal(pendingRecordingMode.value || 'microphone', resumeContext);+ try {+ await startRecordingInternal(pendingRecordingMode.value || 'microphone', resumeContext);+ } finally {+ isPreparingRecording.value = false;+ }};// Cancel recording disclaimer@@ -446,37 +595,68 @@ export function useAudio(state, utils) {// as a toggle in the upload modal next to the mic// button and persisted in localStorage.const skipProc = disableAudioProcessing && disableAudioProcessing.value;- const buildConstraints = (deviceId) => {- const c = {- echoCancellation: !skipProc,- noiseSuppression: !skipProc,- autoGainControl: !skipProc,- sampleRate: 48000- };- if (deviceId) c.deviceId = { exact: deviceId };- return c;- };+ let primaryDeviceId = (selectedMicDeviceId && selectedMicDeviceId.value) || '';++ // Acquire first, then enumerate. Browsers reveal useful+ // device labels only after the normal microphone permission+ // grant initiated by the user's click.+ let primaryResult = await acquireMicrophoneStream(navigator.mediaDevices, {+ deviceId: primaryDeviceId,+ disableAudioProcessing: skipProc+ });+ let micStreamA = primaryResult.stream;+ activeStreams.value = [micStreamA];- const primaryDeviceId = (selectedMicDeviceId && selectedMicDeviceId.value) || '';- const secondaryDeviceId = (selectedSecondaryDeviceId && selectedSecondaryDeviceId.value) || '';- const wantsMix = !!secondaryDeviceId && secondaryDeviceId !== primaryDeviceId;+ if (primaryResult.usedFallback) {+ primaryDeviceId = '';+ if (selectedMicDeviceId) selectedMicDeviceId.value = '';+ showSelectedMicrophoneUnavailable();+ }- // Primary stream (the user's mic, or whatever they- // explicitly picked as the primary input).- const micStreamA = await navigator.mediaDevices.getUserMedia({- audio: buildConstraints(primaryDeviceId)- });+ const refreshedInputs = await refreshAudioDeviceLists();+ const activeDeviceId = micStreamA.getAudioTracks()[0]?.getSettings?.().deviceId || '';++ // Mobile browsers generally lack the desktop browser's own+ // microphone chooser. Only offer Speakr's inline fallback on+ // mobile, when no explicit selection is active and the browser+ // exposes a confidently separate physical input. Desktop keeps+ // its native chooser without a second automatic selection step.+ if (!primaryDeviceId && shouldAutoOfferExternalAudioInput()) {+ const candidates = findExternalAudioInputCandidates(refreshedInputs, activeDeviceId);+ const candidateSignature = getAudioInputCandidateSignature(candidates);+ if (candidates.length > 0+ && candidateSignature+ && candidateSignature !== dismissedMicrophoneCandidateSignature) {+ const selection = await waitForMicrophoneSelection(candidates, activeDeviceId);+ if (selection.action === 'cancel') {+ micStreamA.getTracks().forEach(track => track.stop());+ activeStreams.value = [];+ return;+ }- // Now that the user has granted mic permission,- // device labels populate — re-scan for virtual audio- // routing devices (BlackHole / VB-Cable / monitor- // sources) so the upload modal can offer them. Also- // refresh the full input-device list for the picker- // (post-permission the labels are real names instead- // of opaque IDs).- if (utils.refreshVirtualAudioDevices) utils.refreshVirtualAudioDevices();- if (utils.refreshInputAudioDevices) utils.refreshInputAudioDevices();+ if (selection.action === 'select' && selection.deviceId) {+ primaryDeviceId = selection.deviceId;+ if (primaryDeviceId !== activeDeviceId) {+ micStreamA.getTracks().forEach(track => track.stop());+ activeStreams.value = [];+ primaryResult = await acquireMicrophoneStream(navigator.mediaDevices, {+ deviceId: primaryDeviceId,+ disableAudioProcessing: skipProc+ });+ micStreamA = primaryResult.stream;+ activeStreams.value = [micStreamA];+ if (primaryResult.usedFallback) {+ primaryDeviceId = '';+ if (selectedMicDeviceId) selectedMicDeviceId.value = '';+ showSelectedMicrophoneUnavailable();+ }+ }+ }+ }+ }+ const secondaryDeviceId = (selectedSecondaryDeviceId && selectedSecondaryDeviceId.value) || '';+ const wantsMix = !!secondaryDeviceId && secondaryDeviceId !== primaryDeviceId;audioContext.value = new (window.AudioContext || window.webkitAudioContext)();if (wantsMix) {@@ -491,10 +671,14 @@ export function useAudio(state, utils) {let micStreamB;try {micStreamB = await navigator.mediaDevices.getUserMedia({- audio: buildConstraints(secondaryDeviceId)+ audio: buildMicrophoneConstraints(secondaryDeviceId, skipProc)});} catch (mixErr) {console.warn('[Recording] Secondary input unavailable, falling back to primary only:', mixErr);+ if (isUnavailableAudioInputError(mixErr) && selectedSecondaryDeviceId) {+ selectedSecondaryDeviceId.value = '';+ refreshAudioDeviceLists();+ }if (utils.showToast) utils.showToast('Secondary input unavailable — recording primary only.','fa-exclamation-triangle'@@ -596,17 +780,22 @@ export function useAudio(state, utils) {if (!canRecordAudio.value || !canRecordSystemAudio.value) {throw new Error('Recording is not available. Make sure you are using HTTPS.');}- // Honour the disableAudioProcessing flag here too —- // see comment at the microphone-only path above.+ // Honour the chosen primary input and the processing flag+ // here too. Display capture was already acquired first in+ // startRecording(), preserving Firefox's transient activation.const skipProcBoth = disableAudioProcessing && disableAudioProcessing.value;- const micStream = await navigator.mediaDevices.getUserMedia({- audio: {- echoCancellation: !skipProcBoth,- noiseSuppression: !skipProcBoth,- autoGainControl: !skipProcBoth,- sampleRate: 48000- }+ const selectedDeviceId = (selectedMicDeviceId && selectedMicDeviceId.value) || '';+ const micResult = await acquireMicrophoneStream(navigator.mediaDevices, {+ deviceId: selectedDeviceId,+ disableAudioProcessing: skipProcBoth});+ const micStream = micResult.stream;+ activeStreams.value = [micStream];+ if (micResult.usedFallback) {+ if (selectedMicDeviceId) selectedMicDeviceId.value = '';+ showSelectedMicrophoneUnavailable();+ }+ await refreshAudioDeviceLists();// Use pre-obtained display stream or get it nowconst isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;@@ -1646,6 +1835,11 @@ export function useAudio(state, utils) {return {startRecording,+ requestMicrophonePermission,+ confirmPendingMicrophoneSelection,+ cancelPendingMicrophoneSelection,+ isPreparingRecording,+ pendingMicrophoneSelection,pauseRecording,resumeRecording,stopRecording,diff --git a/static/js/modules/composables/audio.test.js b/static/js/modules/composables/audio.test.jsnew file mode 100644index 00000000..11d78b3b--- /dev/null+++ b/static/js/modules/composables/audio.test.js@@ -0,0 +1,112 @@+import { describe, expect, it, vi } from 'vitest';++import {+ acquireMicrophoneStream,+ buildMicrophoneConstraints,+ isUnavailableAudioInputError+} from './audio.js';++const stream = (name) => ({ name, getTracks: () => [] });+const mediaError = (name) => Object.assign(new Error(name), { name });++describe('microphone acquisition helpers', () => {+ it('builds exact device constraints for a selected input', () => {+ expect(buildMicrophoneConstraints('usb-mic', false)).toEqual({+ echoCancellation: true,+ noiseSuppression: true,+ autoGainControl: true,+ sampleRate: 48000,+ deviceId: { exact: 'usb-mic' }+ });+ });++ it('omits deviceId for the system default and can disable processing', () => {+ expect(buildMicrophoneConstraints('', true)).toEqual({+ echoCancellation: false,+ noiseSuppression: false,+ autoGainControl: false,+ sampleRate: 48000+ });+ });++ it.each(['NotFoundError', 'OverconstrainedError'])('recognizes %s as unavailable input errors', (name) => {+ expect(isUnavailableAudioInputError(mediaError(name))).toBe(true);+ });++ it('does not classify permission or hardware errors as stale selections', () => {+ expect(isUnavailableAudioInputError(mediaError('NotAllowedError'))).toBe(false);+ expect(isUnavailableAudioInputError(mediaError('NotReadableError'))).toBe(false);+ });++ it('returns an exact selected stream without retrying', async () => {+ const selectedStream = stream('selected');+ const getUserMedia = vi.fn().mockResolvedValue(selectedStream);++ await expect(acquireMicrophoneStream({ getUserMedia }, {+ deviceId: 'usb-mic',+ disableAudioProcessing: false+ })).resolves.toEqual({+ stream: selectedStream,+ requestedDeviceId: 'usb-mic',+ usedFallback: false,+ originalError: null+ });+ expect(getUserMedia).toHaveBeenCalledOnce();+ expect(getUserMedia).toHaveBeenCalledWith({+ audio: expect.objectContaining({ deviceId: { exact: 'usb-mic' } })+ });+ });++ it.each(['NotFoundError', 'OverconstrainedError'])('retries %s once with the default input', async (name) => {+ const originalError = mediaError(name);+ const fallbackStream = stream('fallback');+ const getUserMedia = vi.fn()+ .mockRejectedValueOnce(originalError)+ .mockResolvedValueOnce(fallbackStream);++ await expect(acquireMicrophoneStream({ getUserMedia }, {+ deviceId: 'missing-mic',+ disableAudioProcessing: true+ })).resolves.toEqual({+ stream: fallbackStream,+ requestedDeviceId: 'missing-mic',+ usedFallback: true,+ originalError+ });+ expect(getUserMedia).toHaveBeenCalledTimes(2);+ expect(getUserMedia.mock.calls[0][0].audio.deviceId).toEqual({ exact: 'missing-mic' });+ expect(getUserMedia.mock.calls[1][0].audio).not.toHaveProperty('deviceId');+ });++ it.each(['NotAllowedError', 'SecurityError', 'NotReadableError'])('does not retry %s', async (name) => {+ const error = mediaError(name);+ const getUserMedia = vi.fn().mockRejectedValue(error);++ await expect(acquireMicrophoneStream({ getUserMedia }, {+ deviceId: 'usb-mic'+ })).rejects.toBe(error);+ expect(getUserMedia).toHaveBeenCalledOnce();+ });++ it('does not retry a failure when the system default was requested', async () => {+ const error = mediaError('NotFoundError');+ const getUserMedia = vi.fn().mockRejectedValue(error);++ await expect(acquireMicrophoneStream({ getUserMedia }, {+ deviceId: ''+ })).rejects.toBe(error);+ expect(getUserMedia).toHaveBeenCalledOnce();+ });++ it('propagates a failed fallback without looping', async () => {+ const fallbackError = mediaError('NotReadableError');+ const getUserMedia = vi.fn()+ .mockRejectedValueOnce(mediaError('NotFoundError'))+ .mockRejectedValueOnce(fallbackError);++ await expect(acquireMicrophoneStream({ getUserMedia }, {+ deviceId: 'missing-mic'+ })).rejects.toBe(fallbackError);+ expect(getUserMedia).toHaveBeenCalledTimes(2);+ });+});diff --git a/static/js/modules/utils/platform.js b/static/js/modules/utils/platform.jsindex 2ff781ec..ce8bc253 100644--- a/static/js/modules/utils/platform.js+++ b/static/js/modules/utils/platform.js@@ -31,10 +31,63 @@ const KNOWN_VIRTUAL_DEVICE_HINTS = [{ match: /what u hear/i, os: 'Windows', name: 'What U Hear' },// Linux{ match: /monitor of /i, os: 'Linux', name: 'PulseAudio Monitor' },+ { match: /monitor source/i, os: 'Linux', name: 'PulseAudio Monitor' },{ match: /pipewire.*monitor/i, os: 'Linux', name: 'PipeWire Monitor' },{ match: /pulse.*monitor/i, os: 'Linux', name: 'PulseAudio Monitor' },];+const EXTERNAL_INPUT_LABEL_HINT = /\b(?:usb|external|wireless|bluetooth|headset|receiver|webcam|camera|audio interface|audio codec)\b/i;+const INTERNAL_INPUT_LABEL_HINT = /\b(?:built[- ]?in|internal|phone|handset|microphone array|bottom mic|top mic|front mic|rear mic)\b/i;+const GENERIC_INPUT_LABEL = /^(?:default|communications|microphone(?:\s*\d+)?|earpiece|headset earpiece|speakerphone)$/i;++function findVirtualDeviceHint(label) {+ if (!label) return null;+ return KNOWN_VIRTUAL_DEVICE_HINTS.find(hint => hint.match.test(label)) || null;+}++export function isVirtualAudioDeviceLabel(label) {+ return !!findVirtualDeviceHint(label);+}++export function normalizeAudioInputDevices(devices = []) {+ return devices+ .filter(device => device && (!device.kind || device.kind === 'audioinput'))+ .map(device => ({+ kind: 'audioinput',+ deviceId: device.deviceId || '',+ label: device.label || '',+ groupId: device.groupId || '',+ isVirtual: isVirtualAudioDeviceLabel(device.label || '')+ }));+}++export function findExternalAudioInputCandidates(devices = [], activeDeviceId = '') {+ const inputs = normalizeAudioInputDevices(devices);+ const active = inputs.find(device => device.deviceId === activeDeviceId) || null;++ return inputs.filter(device => {+ if (!device.deviceId || !device.label || device.isVirtual) return false;+ if (device.deviceId === activeDeviceId) return false;+ if (device.deviceId === 'default' || device.deviceId === 'communications') return false;+ if (GENERIC_INPUT_LABEL.test(device.label) || INTERNAL_INPUT_LABEL_HINT.test(device.label)) return false;+ if (EXTERNAL_INPUT_LABEL_HINT.test(device.label)) return true;++ return !!(+ active?.groupId+ && device.groupId+ && device.groupId !== active.groupId+ );+ });+}++export function getAudioInputCandidateSignature(devices = []) {+ return devices+ .map(device => device?.deviceId || '')+ .filter(Boolean)+ .sort()+ .join('|');+}+/*** Inspect the current user agent + platform string and return a small* normalized descriptor used everywhere else in the audio capture flow.@@ -73,6 +126,10 @@ export function detectPlatform() {return { os, browser };}+export function shouldAutoOfferExternalAudioInput(platform = detectPlatform()) {+ return platform?.os === 'Android' || platform?.os === 'iOS';+}+/*** Returns a structured capability report describing what audio capture* is realistically available on the current browser + OS — for use by@@ -163,19 +220,17 @@ export async function enumerateVirtualAudioDevices() {} catch (_) {return [];}- const inputs = devices.filter(d => d.kind === 'audioinput' && d.label);+ const inputs = normalizeAudioInputDevices(devices).filter(d => d.label);const matches = [];for (const d of inputs) {- for (const hint of KNOWN_VIRTUAL_DEVICE_HINTS) {- if (hint.match.test(d.label)) {- matches.push({- deviceId: d.deviceId,- label: d.label,- virtualToolName: hint.name,- os: hint.os,- });- break;- }+ const hint = findVirtualDeviceHint(d.label);+ if (hint) {+ matches.push({+ deviceId: d.deviceId,+ label: d.label,+ virtualToolName: hint.name,+ os: hint.os,+ });}}return matches;diff --git a/static/js/modules/utils/platform.test.js b/static/js/modules/utils/platform.test.jsnew file mode 100644index 00000000..9c12632f--- /dev/null+++ b/static/js/modules/utils/platform.test.js@@ -0,0 +1,117 @@+import { describe, expect, it } from 'vitest';++import {+ findExternalAudioInputCandidates,+ getAudioInputCandidateSignature,+ isVirtualAudioDeviceLabel,+ normalizeAudioInputDevices,+ shouldAutoOfferExternalAudioInput+} from './platform.js';++const input = (deviceId, label, groupId = '') => ({+ kind: 'audioinput',+ deviceId,+ label,+ groupId+});++describe('audio input device helpers', () => {+ it('normalizes audio inputs and preserves grouping metadata', () => {+ expect(normalizeAudioInputDevices([+ input('mic-1', 'Built-in microphone', 'phone'),+ { kind: 'videoinput', deviceId: 'camera-1', label: 'Camera' }+ ])).toEqual([{+ kind: 'audioinput',+ deviceId: 'mic-1',+ label: 'Built-in microphone',+ groupId: 'phone',+ isVirtual: false+ }]);+ });++ it('recognizes the existing virtual and monitor device labels', () => {+ expect(isVirtualAudioDeviceLabel('BlackHole 2ch')).toBe(true);+ expect(isVirtualAudioDeviceLabel('Monitor Source')).toBe(true);+ expect(isVirtualAudioDeviceLabel('USB Audio Device')).toBe(false);+ });++ it('does not offer another device for a single built-in microphone', () => {+ const devices = [input('phone-mic', 'Built-in microphone', 'phone')];+ expect(findExternalAudioInputCandidates(devices, 'phone-mic')).toEqual([]);+ });++ it('ignores blank labels and browser pseudo-devices', () => {+ const devices = [+ input('phone-mic', 'Built-in microphone', 'phone'),+ input('hidden', '', 'usb'),+ input('default', 'Default', 'usb'),+ input('communications', 'Communications', 'usb')+ ];+ expect(findExternalAudioInputCandidates(devices, 'phone-mic')).toEqual([]);+ });++ it.each([+ 'USB Audio Device',+ 'Wireless GO II RX',+ 'Bluetooth Headset',+ 'Logitech Webcam Microphone',+ 'External Audio Interface'+ ])('offers a likely external input labelled %s', (label) => {+ const devices = [+ input('phone-mic', 'Built-in microphone', 'phone'),+ input('external-mic', label, 'external')+ ];+ expect(findExternalAudioInputCandidates(devices, 'phone-mic'))+ .toMatchObject([{ deviceId: 'external-mic', label }]);+ });++ it('uses a distinct group as a conservative fallback for a named device', () => {+ const devices = [+ input('phone-mic', 'Primary microphone', 'phone'),+ input('interface', 'Scarlett 2i2', 'interface')+ ];+ expect(findExternalAudioInputCandidates(devices, 'phone-mic'))+ .toMatchObject([{ deviceId: 'interface' }]);+ });++ it('does not infer an external input from group data without an active group', () => {+ expect(findExternalAudioInputCandidates([+ input('interface', 'Scarlett 2i2', 'interface')+ ], '')).toEqual([]);+ });++ it('excludes internal and virtual alternatives', () => {+ const devices = [+ input('phone-mic', 'Primary microphone', 'phone'),+ input('rear-mic', 'Rear mic', 'rear'),+ input('earpiece', 'Headset earpiece', 'headset'),+ input('speakerphone', 'Speakerphone', 'speaker'),+ input('blackhole', 'BlackHole 2ch', 'virtual')+ ];+ expect(findExternalAudioInputCandidates(devices, 'phone-mic')).toEqual([]);+ });++ it('excludes the currently active input', () => {+ const devices = [input('usb-mic', 'USB Audio Device', 'usb')];+ expect(findExternalAudioInputCandidates(devices, 'usb-mic')).toEqual([]);+ });++ it.each(['Android', 'iOS'])('allows the automatic external-input offer on %s', (os) => {+ expect(shouldAutoOfferExternalAudioInput({ os })).toBe(true);+ });++ it.each(['Windows', 'macOS', 'Linux', 'ChromeOS', 'unknown'])(+ 'leaves microphone selection to the browser on desktop platform %s',+ (os) => {+ expect(shouldAutoOfferExternalAudioInput({ os })).toBe(false);+ }+ );++ it('produces a stable candidate signature regardless of enumeration order', () => {+ const first = [input('b', 'USB B'), input('a', 'USB A')];+ const second = [input('a', 'USB A'), input('b', 'USB B')];+ expect(getAudioInputCandidateSignature(first)).toBe('a|b');+ expect(getAudioInputCandidateSignature(second)).toBe('a|b');+ expect(getAudioInputCandidateSignature([input('a', 'USB A')])).toBe('a');+ });+});diff --git a/static/locales/de.json b/static/locales/de.jsonindex efe876be..7faf3b4c 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -1271,7 +1271,9 @@"recording": {"acceptDisclaimer": "Ich akzeptiere","alsoMixIn": "Zusätzlich einmischen (optional)",+ "anotherMicAvailable": "Ein weiteres Mikrofon ist verfügbar","cancelRecording": "Abbrechen",+ "chooseMicBeforeRecording": "Wählen Sie den gewünschten Eingang. Die Aufnahme hat noch nicht begonnen.","detectedDevicePrefix": "Erkannt:","detectedDeviceSuffix": "— wählen Sie es im Mikrofon-Dropdown, um System-Audio einzuleiten.","disableAudioProcessingHelp": "— aktivieren Sie diese Option, wenn Sie System-Audio über eine Monitor-Quelle oder ein virtuelles Audiogerät (BlackHole, VB-Cable, Pulse-Monitor) einleiten. Bei normaler Mikrofonaufnahme deaktiviert lassen.",@@ -1288,6 +1290,8 @@"microphone": "Mikrofon","microphoneAndSystem": "Mikrofon + System","microphonePermissionDenied": "Mikrofon-Berechtigung verweigert",+ "micPermissionFailed": "Auf das Mikrofon konnte nicht zugegriffen werden. Prüfen Sie, ob es verbunden und nicht anderweitig belegt ist.",+ "micPermissionUnavailable": "Mikrofonzugriff ist nicht verfügbar. Stellen Sie sicher, dass Sie HTTPS verwenden.","mixHelp": "Wählen Sie ein Monitor / virtuelles Audiogerät (BlackHole auf macOS, VB-Cable auf Windows oder ein gewrapptes Pulse-Monitor unter Linux), um System-Audio mit Ihrem Mikrofon zu mischen. Beide Streams werden zu einer Aufnahme kombiniert.","mixingTwoInputs": "Mische 2 Eingänge","modeBoth": "Mikrofon + System",@@ -1318,6 +1322,7 @@"restoreRecording": "Wiederherstellen","resumeRecording": "Fortsetzen","saveRecording": "Aufnahme speichern",+ "selectedMicUnavailable": "Das ausgewählte Mikrofon ist nicht mehr verfügbar. Der Systemstandard wird verwendet.","size": "Größe","startRecording": "Aufnahme starten","startedAt": "Gestartet am",diff --git a/static/locales/en.json b/static/locales/en.jsonindex 9fe663fb..6d1d471f 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -1280,7 +1280,9 @@"recording": {"acceptDisclaimer": "I Accept","alsoMixIn": "Also mix in (optional)",+ "anotherMicAvailable": "Another microphone is available","cancelRecording": "Cancel",+ "chooseMicBeforeRecording": "Choose the input you want to use. Recording has not started yet.","detectedDevicePrefix": "Detected","detectedDeviceSuffix": "— pick it from the microphone dropdown to route system audio in.","disableAudioProcessingHelp": "— enable when you're routing system audio in through a monitor source or virtual audio device (BlackHole, VB-Cable, Pulse monitor). Leave off for normal microphone recording.",@@ -1297,6 +1299,8 @@"microphone": "Microphone","microphoneAndSystem": "Microphone + System","microphonePermissionDenied": "Microphone permission denied",+ "micPermissionFailed": "Could not access the microphone. Check that it is connected and not in use.",+ "micPermissionUnavailable": "Microphone access is not available. Make sure you are using HTTPS.","mixHelp": "Pick a monitor / virtual audio device (BlackHole on macOS, VB-Cable on Windows, or a wrapped Pulse monitor on Linux) to mix system audio with your mic. Both streams combine into one recording.","mixingTwoInputs": "Mixing 2 inputs","modeBoth": "Microphone + System",@@ -1327,6 +1331,7 @@"restoreRecording": "Restore","resumeRecording": "Resume","saveRecording": "Save Recording",+ "selectedMicUnavailable": "The selected microphone is no longer available. Using the system default.","size": "Size","startRecording": "Start Recording","startedAt": "Started At",diff --git a/static/locales/es.json b/static/locales/es.jsonindex c9c61d32..5cd7d998 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -1271,7 +1271,9 @@"recording": {"acceptDisclaimer": "Acepto","alsoMixIn": "Mezclar también (opcional)",+ "anotherMicAvailable": "Hay otro micrófono disponible","cancelRecording": "Cancelar",+ "chooseMicBeforeRecording": "Elige la entrada que deseas usar. La grabación aún no ha comenzado.","detectedDevicePrefix": "Detectado","detectedDeviceSuffix": "— selecciónalo en el menú de micrófono para enrutar el audio del sistema.","disableAudioProcessingHelp": "— activa esta opción cuando enrutes audio del sistema a través de un monitor o dispositivo de audio virtual (BlackHole, VB-Cable, monitor de Pulse). Déjala desactivada para una grabación normal de micrófono.",@@ -1288,6 +1290,8 @@"microphone": "Micrófono","microphoneAndSystem": "Micrófono + Sistema","microphonePermissionDenied": "Permiso del micrófono denegado",+ "micPermissionFailed": "No se pudo acceder al micrófono. Comprueba que esté conectado y no esté en uso.",+ "micPermissionUnavailable": "El acceso al micrófono no está disponible. Asegúrate de usar HTTPS.","mixHelp": "Elige un dispositivo de monitor / audio virtual (BlackHole en macOS, VB-Cable en Windows, o un monitor de Pulse encapsulado en Linux) para mezclar el audio del sistema con tu micrófono. Ambas señales se combinan en una sola grabación.","mixingTwoInputs": "Mezclando 2 entradas","modeBoth": "Micrófono + Sistema",@@ -1318,6 +1322,7 @@"restoreRecording": "Restaurar","resumeRecording": "Reanudar","saveRecording": "Guardar Grabación",+ "selectedMicUnavailable": "El micrófono seleccionado ya no está disponible. Se usará el predeterminado del sistema.","size": "Tamaño","startRecording": "Iniciar Grabación","startedAt": "Iniciado el",diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex f1a7103f..202933e9 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -1271,7 +1271,9 @@"recording": {"acceptDisclaimer": "J'accepte","alsoMixIn": "Mixer aussi (optionnel)",+ "anotherMicAvailable": "Un autre microphone est disponible","cancelRecording": "Annuler",+ "chooseMicBeforeRecording": "Choisissez l'entrée à utiliser. L'enregistrement n'a pas encore commencé.","detectedDevicePrefix": "Détecté :","detectedDeviceSuffix": "— sélectionnez-le dans la liste du micro pour acheminer l'audio système.","disableAudioProcessingHelp": "— activez cette option lorsque vous acheminez l'audio système via un monitor ou un périphérique audio virtuel (BlackHole, VB-Cable, monitor PulseAudio). Laissez désactivé pour un enregistrement microphone normal.",@@ -1288,6 +1290,8 @@"microphone": "Microphone","microphoneAndSystem": "Microphone + Système","microphonePermissionDenied": "Permission du microphone refusée",+ "micPermissionFailed": "Impossible d'accéder au microphone. Vérifiez qu'il est connecté et qu'aucune autre application ne l'utilise.",+ "micPermissionUnavailable": "L'accès au microphone n'est pas disponible. Vérifiez que vous utilisez HTTPS.","mixHelp": "Choisissez un monitor / périphérique audio virtuel (BlackHole sur macOS, VB-Cable sur Windows, ou un monitor Pulse encapsulé sous Linux) pour mixer l'audio système avec votre micro. Les deux flux se combinent en un seul enregistrement.","mixingTwoInputs": "Mixage de 2 entrées","modeBoth": "Microphone + Système",@@ -1318,6 +1322,7 @@"restoreRecording": "Restaurer","resumeRecording": "Reprendre","saveRecording": "Enregistrer l'Enregistrement",+ "selectedMicUnavailable": "Le microphone sélectionné n'est plus disponible. Le périphérique système par défaut sera utilisé.","size": "Taille","startRecording": "Démarrer l'Enregistrement","startedAt": "Commencé le",diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex ffc45553..370956d6 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -1271,7 +1271,9 @@"recording": {"acceptDisclaimer": "Eu Aceito","alsoMixIn": "Também misturar (opcional)",+ "anotherMicAvailable": "Outro microfone está disponível","cancelRecording": "Cancelar",+ "chooseMicBeforeRecording": "Escolha a entrada que deseja usar. A gravação ainda não começou.","detectedDevicePrefix": "Detectado:","detectedDeviceSuffix": "— selecione no menu de microfone para encaminhar o áudio do sistema.","disableAudioProcessingHelp": "— ative ao encaminhar áudio do sistema via uma fonte monitor ou dispositivo de áudio virtual (BlackHole, VB-Cable, monitor do Pulse). Deixe desativado para gravação normal de microfone.",@@ -1288,6 +1290,8 @@"microphone": "Microfone","microphoneAndSystem": "Microfone + Sistema","microphonePermissionDenied": "Permissão do microfone negada",+ "micPermissionFailed": "Não foi possível acessar o microfone. Verifique se ele está conectado e não está em uso.",+ "micPermissionUnavailable": "O acesso ao microfone não está disponível. Verifique se você está usando HTTPS.","mixHelp": "Escolha um dispositivo monitor / áudio virtual (BlackHole no macOS, VB-Cable no Windows ou um monitor do Pulse encapsulado no Linux) para misturar áudio do sistema com seu microfone. Ambas as faixas se combinam em uma única gravação.","mixingTwoInputs": "Misturando 2 entradas","modeBoth": "Microfone + Sistema",@@ -1318,6 +1322,7 @@"restoreRecording": "Restaurar","resumeRecording": "Retomar","saveRecording": "Salvar Gravação",+ "selectedMicUnavailable": "O microfone selecionado não está mais disponível. O padrão do sistema será usado.","size": "Tamanho","startRecording": "Iniciar Gravação","startedAt": "Iniciado em",diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex 0c8195f3..203b2c03 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -1271,7 +1271,9 @@"recording": {"acceptDisclaimer": "Принимаю","alsoMixIn": "Также подмешать (опционально)",+ "anotherMicAvailable": "Доступен ещё один микрофон","cancelRecording": "Отмена",+ "chooseMicBeforeRecording": "Выберите нужный вход. Запись ещё не началась.","detectedDevicePrefix": "Обнаружено:","detectedDeviceSuffix": "— выберите его в списке микрофонов, чтобы направить системный звук.","disableAudioProcessingHelp": "— включите, когда направляете системный звук через monitor-источник или виртуальное аудиоустройство (BlackHole, VB-Cable, Pulse monitor). Оставьте выключенным для обычной записи с микрофона.",@@ -1288,6 +1290,8 @@"microphone": "Микрофон","microphoneAndSystem": "Микрофон + система","microphonePermissionDenied": "Доступ к микрофону запрещён",+ "micPermissionFailed": "Не удалось получить доступ к микрофону. Проверьте, что он подключён и не используется другим приложением.",+ "micPermissionUnavailable": "Доступ к микрофону недоступен. Убедитесь, что используется HTTPS.","mixHelp": "Выберите monitor / виртуальное аудиоустройство (BlackHole на macOS, VB-Cable на Windows или обёрнутый Pulse monitor на Linux), чтобы смешать системный звук с микрофоном. Оба потока объединяются в одну запись.","mixingTwoInputs": "Смешиваются 2 входа","modeBoth": "Микрофон + система",@@ -1318,6 +1322,7 @@"restoreRecording": "Восстановить","resumeRecording": "Возобновить","saveRecording": "Сохранить запись",+ "selectedMicUnavailable": "Выбранный микрофон больше недоступен. Будет использован системный микрофон по умолчанию.","size": "Размер","startRecording": "Начать запись","startedAt": "Начато в",diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 3e1751ca..1e56ccd0 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -1271,7 +1271,9 @@"recording": {"acceptDisclaimer": "我接受","alsoMixIn": "同时混入(可选)",+ "anotherMicAvailable": "检测到另一个可用麦克风","cancelRecording": "取消",+ "chooseMicBeforeRecording": "请选择要使用的输入设备。录音尚未开始。","detectedDevicePrefix": "已检测到","detectedDeviceSuffix": "— 在麦克风下拉菜单中选择它,以将系统音频路由进来。","disableAudioProcessingHelp": "— 当您通过 monitor 源或虚拟音频设备(BlackHole、VB-Cable、Pulse monitor)路由系统音频时启用。普通麦克风录音时请保持关闭。",@@ -1288,6 +1290,8 @@"microphone": "麦克风","microphoneAndSystem": "麦克风 + 系统","microphonePermissionDenied": "麦克风权限被拒绝",+ "micPermissionFailed": "无法访问麦克风。请确认设备已连接且未被其他应用占用。",+ "micPermissionUnavailable": "麦克风访问不可用。请确认正在使用 HTTPS。","mixHelp": "选择一个 monitor / 虚拟音频设备(macOS 上的 BlackHole、Windows 上的 VB-Cable,或 Linux 上包装好的 Pulse monitor),将系统音频与您的麦克风混合。两路音频流将合并为一段录音。","mixingTwoInputs": "正在混合 2 个输入","modeBoth": "麦克风 + 系统",@@ -1318,6 +1322,7 @@"restoreRecording": "恢复","resumeRecording": "恢复","saveRecording": "保存录音",+ "selectedMicUnavailable": "所选麦克风已不可用,将使用系统默认输入。","size": "大小","startRecording": "开始录音","startedAt": "开始时间",diff --git a/templates/components/upload-view.html b/templates/components/upload-view.htmlindex 09fc1666..4b16bc97 100644--- a/templates/components/upload-view.html+++ b/templates/components/upload-view.html@@ -234,7 +234,9 @@dot left of the label so the function is stillobvious without being loud. --><button @click="startRecording('microphone')"- class="w-full px-3 py-2.5 rounded-lg flex items-center justify-center gap-2 text-sm font-medium transition-colors"+ :disabled="isPreparingRecording"+ :class="{ 'opacity-60 cursor-wait': isPreparingRecording }"+ class="w-full px-3 py-2.5 rounded-lg flex items-center justify-center gap-2 text-sm font-medium transition-colors disabled:pointer-events-none"style="background: var(--bg-tertiary); color: var(--text-primary); border: 1px solid var(--border-secondary);"onmouseover="this.style.borderColor='var(--text-accent)'" onmouseout="this.style.borderColor='var(--border-secondary)'"><span class="w-2 h-2 rounded-full bg-red-500 flex-shrink-0"></span>@@ -249,7 +251,9 @@"tab-audio-only" indicator dot is preserved. --><div v-if="canRecordSystemAudio" class="grid grid-cols-2 gap-2"><button @click="startRecording('system')"- class="relative px-3 py-2 rounded-lg flex items-center justify-center gap-1.5 text-xs font-medium transition-colors"+ :disabled="isPreparingRecording"+ :class="{ 'opacity-60 cursor-wait': isPreparingRecording }"+ class="relative px-3 py-2 rounded-lg flex items-center justify-center gap-1.5 text-xs font-medium transition-colors disabled:pointer-events-none"style="background: var(--bg-tertiary); color: var(--text-secondary); border: 1px solid var(--border-secondary);"onmouseover="this.style.borderColor='var(--text-accent)'" onmouseout="this.style.borderColor='var(--border-secondary)'"><span v-if="audioCaps && audioCaps.supportsTabAudio && !audioCaps.supportsSystemAudio"@@ -260,7 +264,9 @@</button><button @click="startRecording('both')"- class="relative px-3 py-2 rounded-lg flex items-center justify-center gap-1 text-xs font-medium transition-colors"+ :disabled="isPreparingRecording"+ :class="{ 'opacity-60 cursor-wait': isPreparingRecording }"+ class="relative px-3 py-2 rounded-lg flex items-center justify-center gap-1 text-xs font-medium transition-colors disabled:pointer-events-none"style="background: var(--bg-tertiary); color: var(--text-secondary); border: 1px solid var(--border-secondary);"onmouseover="this.style.borderColor='var(--text-accent)'" onmouseout="this.style.borderColor='var(--border-secondary)'"><span v-if="audioCaps && audioCaps.supportsTabAudio && !audioCaps.supportsSystemAudio"@@ -320,7 +326,9 @@getUserMedia briefly to populate them. Theaudio-processing opt-out lives inside this grouptoo since it's a device-level capture setting. -->- <details class="disclosure-card text-[11px] mt-1 group">+ <details :open="!!pendingMicrophoneSelection"+ @toggle="pendingMicrophoneSelection && !$event.target.open && ($event.target.open = true)"+ class="disclosure-card text-[11px] mt-1 group"><summary class="cursor-pointer flex items-center gap-1 px-2 py-1.5 rounded-md hover:bg-[var(--bg-tertiary)] transition-colors" style="color: var(--text-muted); list-style: none;"><i class="fas fa-sliders-h"></i><span>${ t('recording.inputDevices') }</span>@@ -328,11 +336,23 @@<i class="fas fa-chevron-down ml-auto text-[10px] transition-transform group-open:rotate-180"></i></summary><div class="disclosure-card-body space-y-2">- <div v-if="!inputAudioDevices || inputAudioDevices.length === 0 || !(inputAudioDevices[0] && inputAudioDevices[0].label)"+ <div v-if="pendingMicrophoneSelection"+ class="rounded-md border border-blue-300/60 bg-blue-50/70 dark:border-blue-700/60 dark:bg-blue-950/30 px-2.5 py-2">+ <div class="flex items-start gap-2">+ <i class="fas fa-microphone text-blue-500 mt-0.5"></i>+ <div>+ <p class="font-medium" style="color: var(--text-primary);">${ t('recording.anotherMicAvailable') }</p>+ <p class="text-[10px] mt-0.5" style="color: var(--text-secondary);">${ t('recording.chooseMicBeforeRecording') }</p>+ <p class="text-[10px] mt-1 font-medium" style="color: var(--text-accent);"+ v-text="pendingMicrophoneSelection.candidates.map(d => d.label).join(', ')"></p>+ </div>+ </div>+ </div>+ <div v-if="!inputAudioDevices || inputAudioDevices.length === 0 || !inputAudioDevices.some(d => d.label)"class="text-[11px]" style="color: var(--text-muted);"><i class="fas fa-info-circle mr-1"></i>${ t('recording.grantMicPermissionHint') }- <button @click.prevent="navigator.mediaDevices.getUserMedia({audio:true}).then(s => { s.getTracks().forEach(t => t.stop()); refreshInputAudioDevices(); })"+ <button @click.prevent="requestMicrophonePermission"class="underline mt-1 block" style="color: var(--text-accent);">${ t('recording.requestMicPermission') }</button>@@ -348,6 +368,17 @@</option></select></div>+ <div v-if="pendingMicrophoneSelection" class="flex items-center justify-end gap-2 pb-1">+ <button @click="cancelPendingMicrophoneSelection"+ class="px-2.5 py-1 rounded border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]"+ style="color: var(--text-secondary);">+ ${ t('buttons.cancel') }+ </button>+ <button @click="confirmPendingMicrophoneSelection"+ class="px-2.5 py-1 rounded text-white bg-blue-600 hover:bg-blue-700">+ ${ t('buttons.startRecording') }+ </button>+ </div><div><label class="block text-[11px] mb-1" style="color: var(--text-muted);">${ t('recording.alsoMixIn') }