Fix browser microphone permission prompt and constraints in WebClient
This commit is contained in:
parent
e7bc618b9a
commit
bd73711456
2 changed files with 169 additions and 19 deletions
|
|
@ -2867,6 +2867,126 @@
|
|||
}
|
||||
}
|
||||
|
||||
async function requestLocalMicrophoneStream(preferredDeviceId) {
|
||||
const isLocalhost = window.location.hostname === 'localhost' ||
|
||||
window.location.hostname === '127.0.0.1' ||
|
||||
window.location.hostname === '[::1]';
|
||||
const isSecure = window.isSecureContext || isLocalhost || window.location.protocol === 'https:';
|
||||
|
||||
// Normalize getUserMedia across modern and legacy interfaces
|
||||
const getMedia = (navigator.mediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function')
|
||||
? (c) => navigator.mediaDevices.getUserMedia(c)
|
||||
: (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia)
|
||||
? (c) => new Promise((resolve, reject) => {
|
||||
const legacy = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
|
||||
legacy.call(navigator, c, resolve, reject);
|
||||
})
|
||||
: null;
|
||||
|
||||
if (!getMedia) {
|
||||
if (!isSecure) {
|
||||
showToast('⚠️ Microphone blocked: Browsers require HTTPS or localhost for microphone access. Access via HTTPS or http://localhost:port (or allow insecure origins in chrome://flags).');
|
||||
} else {
|
||||
showToast('⚠️ Microphone API is not supported in this browser environment.');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Try constraint sets from preferred device down to bare audio: true.
|
||||
// NOTE: NEVER constrain sampleRate or channelCount in getUserMedia — hardware microphones
|
||||
// run at OS/driver rates (e.g. 44.1kHz or 48kHz), and rigid constraints trigger OverconstrainedError,
|
||||
// which prevents browsers from ever presenting the permission prompt dialog!
|
||||
const candidates = [];
|
||||
|
||||
if (preferredDeviceId) {
|
||||
candidates.push({
|
||||
audio: {
|
||||
deviceId: { ideal: preferredDeviceId },
|
||||
echoCancellation: { ideal: true },
|
||||
noiseSuppression: { ideal: true },
|
||||
autoGainControl: { ideal: true }
|
||||
},
|
||||
video: false
|
||||
});
|
||||
}
|
||||
|
||||
// Standard audio with ideal DSP capabilities
|
||||
candidates.push({
|
||||
audio: {
|
||||
echoCancellation: { ideal: true },
|
||||
noiseSuppression: { ideal: true },
|
||||
autoGainControl: { ideal: true }
|
||||
},
|
||||
video: false
|
||||
});
|
||||
|
||||
// Bare audio fallback (maximum compatibility, prompts user in any browser)
|
||||
candidates.push({
|
||||
audio: true,
|
||||
video: false
|
||||
});
|
||||
|
||||
let lastError = null;
|
||||
for (const constraints of candidates) {
|
||||
try {
|
||||
const stream = await getMedia(constraints);
|
||||
if (stream && stream.getAudioTracks().length > 0) {
|
||||
return stream;
|
||||
}
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
console.warn('getUserMedia attempt failed with constraints', constraints, err);
|
||||
// If the user explicitly denied permission or security policy blocked it, do not keep looping
|
||||
if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError' || err.name === 'SecurityError') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (lastError) {
|
||||
if (lastError.name === 'NotAllowedError' || lastError.name === 'PermissionDeniedError') {
|
||||
showToast('⚠️ Microphone permission was denied or blocked. Click the lock/settings icon in your browser address bar to allow microphone access, then click [⚠️ Allow Mic].');
|
||||
} else if (lastError.name === 'NotFoundError' || lastError.name === 'DevicesNotFoundError') {
|
||||
showToast('⚠️ No microphone hardware found on this device. Joined in listen-only mode.');
|
||||
} else if (lastError.name === 'NotReadableError' || lastError.name === 'TrackStartError') {
|
||||
showToast('⚠️ Microphone is currently in use by another application or OS audio service.');
|
||||
} else if (lastError.name === 'OverconstrainedError') {
|
||||
showToast(`⚠️ Microphone device constraint could not be satisfied (${lastError.constraint || 'device'}).`);
|
||||
} else if (lastError.name === 'SecurityError') {
|
||||
showToast('⚠️ Microphone blocked by browser security policy (requires HTTPS or localhost).');
|
||||
} else {
|
||||
showToast(`⚠️ Microphone access failed: ${lastError.message || lastError.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function attachLocalTrackToActivePeerConnections() {
|
||||
if (!state.voiceLocalStream) return;
|
||||
const audioTrack = state.voiceLocalStream.getAudioTracks()[0];
|
||||
if (!audioTrack) return;
|
||||
|
||||
for (const peerId of Object.keys(state.voicePeerConnections)) {
|
||||
const entry = state.voicePeerConnections[peerId];
|
||||
if (!entry || !entry.pc) continue;
|
||||
|
||||
const senders = typeof entry.pc.getSenders === 'function' ? entry.pc.getSenders() : [];
|
||||
const audioSender = senders.find(s => s.track && s.track.kind === 'audio') ||
|
||||
senders.find(s => !s.track);
|
||||
|
||||
if (audioSender && typeof audioSender.replaceTrack === 'function') {
|
||||
audioSender.replaceTrack(audioTrack).catch(err => console.warn('replaceTrack failed', err));
|
||||
} else {
|
||||
try {
|
||||
entry.pc.addTrack(audioTrack, state.voiceLocalStream);
|
||||
} catch {
|
||||
// Ignore duplicate track
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureLocalVoiceMedia() {
|
||||
const AudioCtx = window.AudioContext || window.webkitAudioContext;
|
||||
if (!state.voiceAudioCtx && AudioCtx) {
|
||||
|
|
@ -2888,22 +3008,17 @@
|
|||
}
|
||||
}
|
||||
|
||||
if (!state.voiceLocalStream && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
||||
try {
|
||||
const audioConstraints = {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
channelCount: 1,
|
||||
sampleRate: 16000
|
||||
};
|
||||
if (state.selectedMicDeviceId) {
|
||||
audioConstraints.deviceId = { ideal: state.selectedMicDeviceId };
|
||||
const hasLiveAudioTrack = state.voiceLocalStream &&
|
||||
state.voiceLocalStream.getAudioTracks().some(t => t.readyState === 'live');
|
||||
|
||||
if (!hasLiveAudioTrack) {
|
||||
if (state.voiceLocalStream) {
|
||||
stopLocalVoiceMedia();
|
||||
}
|
||||
state.voiceLocalStream = await navigator.mediaDevices.getUserMedia({ audio: audioConstraints, video: false });
|
||||
state.voiceLocalStream = await requestLocalMicrophoneStream(state.selectedMicDeviceId);
|
||||
if (state.voiceLocalStream) {
|
||||
await enumerateVoiceDevices();
|
||||
} catch (err) {
|
||||
showToast('⚠️ Microphone unavailable or permission denied. Joined in listen-only mode.');
|
||||
attachLocalTrackToActivePeerConnections();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -3408,7 +3523,9 @@
|
|||
const cand = entry.candidateQueue.shift();
|
||||
await entry.pc.addIceCandidate(new window.RTCIceCandidate(cand));
|
||||
}
|
||||
const answer = await entry.pc.createAnswer();
|
||||
const answer = await entry.pc.createAnswer({
|
||||
offerToReceiveAudio: true
|
||||
});
|
||||
await entry.pc.setLocalDescription(answer);
|
||||
sendEnvelope('VOICE_SIGNAL', {
|
||||
channelId: chId,
|
||||
|
|
@ -3630,7 +3747,31 @@
|
|||
updateVoiceCallUI();
|
||||
}
|
||||
|
||||
function toggleVoiceMute(explicitMute) {
|
||||
async function toggleVoiceMute(explicitMute) {
|
||||
if (!state.voiceLocalStream) {
|
||||
// Re-request microphone permissions on click
|
||||
state.voiceLocalStream = await requestLocalMicrophoneStream(state.selectedMicDeviceId);
|
||||
if (state.voiceLocalStream) {
|
||||
state.voiceMuted = false;
|
||||
await enumerateVoiceDevices();
|
||||
attachLocalTrackToActivePeerConnections();
|
||||
await ensureLocalVoiceMedia();
|
||||
if (state.currentVoiceChannelId) {
|
||||
sendEnvelope('VOICE_STATE_UPDATE', {
|
||||
channelId: state.currentVoiceChannelId,
|
||||
isMuted: state.voiceMuted,
|
||||
isDeafened: state.voiceDeafened,
|
||||
transportMode: state.voiceTransportMode
|
||||
});
|
||||
}
|
||||
updateVoiceCallUI();
|
||||
return;
|
||||
} else {
|
||||
updateVoiceCallUI();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
state.voiceMuted = explicitMute !== undefined ? !!explicitMute : !state.voiceMuted;
|
||||
if (state.voiceLocalStream) {
|
||||
state.voiceLocalStream.getAudioTracks().forEach(t => {
|
||||
|
|
@ -3820,8 +3961,15 @@
|
|||
}
|
||||
if (el.voiceMuteBtn) {
|
||||
el.voiceMuteBtn.style.display = amInDisplaySession ? 'inline-flex' : 'none';
|
||||
if (!state.voiceLocalStream) {
|
||||
el.voiceMuteBtn.textContent = '[⚠️ Allow Mic]';
|
||||
el.voiceMuteBtn.className = 'btn btn-warning btn-sm';
|
||||
el.voiceMuteBtn.title = 'Microphone permission not granted. Click to allow microphone access.';
|
||||
} else {
|
||||
el.voiceMuteBtn.textContent = state.voiceMuted ? '[🎙️ Unmute]' : '[🎙️ Mute]';
|
||||
el.voiceMuteBtn.className = state.voiceMuted ? 'btn btn-primary btn-sm' : 'btn btn-secondary btn-sm';
|
||||
el.voiceMuteBtn.title = 'Toggle Microphone Mute';
|
||||
}
|
||||
}
|
||||
if (el.voiceDeafenBtn) {
|
||||
el.voiceDeafenBtn.style.display = amInDisplaySession ? 'inline-flex' : 'none';
|
||||
|
|
|
|||
|
|
@ -39,6 +39,8 @@ public class VoiceCallTests : IAsyncLifetime
|
|||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
Environment.SetEnvironmentVariable("GSDCHAT_DISABLE_OS_AUDIO", "1");
|
||||
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
_port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue