Добавить проверку звука в браузере

This commit is contained in:
AidarKC
2026-11-30 11:55:36 +03:00
parent 3f3e93c87d
commit c175a54a01
6 changed files with 130 additions and 65 deletions
+3 -62
View File
@@ -25,6 +25,7 @@ import { dmNotificationTag, dmUnreadLabel } from './services/dm-push-notificatio
import { initCallUiOverlay } from './services/call-ui-service.js';
import { showToast } from './services/channels-ux.js';
import { toUserMessage } from './services/ui-error-texts.js';
import { unlockDmAudio, playDmSignal } from './services/dm-audio.js';
import { KeyRotationClient } from './services/key-rotation-service.js';
import {
handleCallPushAction,
@@ -123,7 +124,6 @@ import * as contactSearchView from './pages/contact-search-view.js';
import * as chatView from './pages/chat-view.js?v=202611170124';
import * as chatMediaView from './pages/chat-media-view.js';
import { isDmChatMuted } from './services/dm-chat-prefs.js';
import { getDevicePref } from './services/device-prefs.js';
import { isDeveloperToolsEnabled } from './services/feature-settings.js';
import * as userProfileView from './pages/user-profile-view.js?v=20261110-pwa-avatar';
import * as userProfileListView from './pages/user-profile-list-view.js';
@@ -281,8 +281,6 @@ let uiUpdateReloadScheduled = false;
let pwaUpdateCheckAttempted = false;
let uiVersionCheckInFlight = false;
let uiVersionPeriodicIntervalId = null;
let hiddenDmAudioContext = null;
let hiddenDmAudioUnlocked = false;
let initialConnectionCompleted = false;
let orientationLockInFlight = false;
let currentChromeCleanup = null;
@@ -666,63 +664,6 @@ function clearKeepAliveEntries() {
}
}
async function unlockHiddenDmAudio() {
try {
const Ctx = window.AudioContext || window.webkitAudioContext;
if (!Ctx) return false;
if (!hiddenDmAudioContext) {
hiddenDmAudioContext = new Ctx();
}
if (hiddenDmAudioContext.state === 'suspended') {
await hiddenDmAudioContext.resume();
}
hiddenDmAudioUnlocked = hiddenDmAudioContext.state === 'running';
return hiddenDmAudioUnlocked;
} catch {
return false;
}
}
async function playDmSignal({ extended = false } = {}) {
try {
// «Звук в открытом приложении» выключен в настройках уведомлений.
if (getDevicePref('dmSound', true) === false) return false;
if (!hiddenDmAudioUnlocked || !hiddenDmAudioContext) return false;
if (hiddenDmAudioContext.state === 'suspended') {
await hiddenDmAudioContext.resume();
}
if (hiddenDmAudioContext.state !== 'running') return false;
const now = hiddenDmAudioContext.currentTime;
const gain = hiddenDmAudioContext.createGain();
gain.connect(hiddenDmAudioContext.destination);
gain.gain.setValueAtTime(0.0001, now);
const pulse = (offsetSec, freqHz, durationSec, peakGain) => {
const osc = hiddenDmAudioContext.createOscillator();
osc.type = 'sine';
osc.frequency.setValueAtTime(freqHz, now + offsetSec);
osc.connect(gain);
gain.gain.exponentialRampToValueAtTime(peakGain, now + offsetSec + 0.01);
gain.gain.exponentialRampToValueAtTime(0.0001, now + offsetSec + durationSec);
osc.start(now + offsetSec);
osc.stop(now + offsetSec + durationSec + 0.02);
};
if (extended) {
pulse(0, 880, 0.18, 0.032);
pulse(0.24, 1174, 0.2, 0.026);
pulse(0.52, 1567, 0.24, 0.02);
} else {
pulse(0, 1046, 0.12, 0.028);
pulse(0.17, 1318, 0.14, 0.022);
}
return true;
} catch {
return false;
}
}
async function tryLockPortraitOrientation() {
if (orientationLockInFlight) return false;
@@ -2160,10 +2101,10 @@ async function init() {
renderApp();
});
document.addEventListener('pointerdown', () => {
void unlockHiddenDmAudio();
void unlockDmAudio();
}, { passive: true });
document.addEventListener('keydown', () => {
void unlockHiddenDmAudio();
void unlockDmAudio();
}, { passive: true });
document.addEventListener('visibilitychange', () => {
if (document.visibilityState !== 'visible') return;
+9 -1
View File
@@ -1919,7 +1919,15 @@
"text_021": "Short signal of a new message",
"text_022": "Hide message text in push notifications",
"text_023": "Do not immediately connect to the server or download messages for notifications. By default, the app tries to decrypt the text on your device and show it in the notification, including on the lock screen. (The message itself, even in encrypted form, is not sent through push notification servers.)",
"text_024": "Could not save notification preference"
"text_024": "Could not save notification preference",
"text_025": "Test browser sound",
"text_026": "Plays a short test signal and checks AudioContext",
"text_027": "Checking…",
"text_028": "Test signal played. If you cannot hear it, check the device volume and silent mode.",
"text_029": "This browser does not support AudioContext",
"text_030": "The browser blocked AudioContext. Allow sound for this page and try again.",
"text_031": "Sound in the open app is disabled. Enable the switch above and try again.",
"text_032": "Could not play the signal. Check browser sound permission and system volume."
},
"solana_rpc_check_view": {
"text_001": "Solana RPC inspection",
+9 -1
View File
@@ -1970,7 +1970,15 @@
"text_021": "Короткий сигнал о новом сообщении",
"text_022": "Не показывать текст сообщений в push-уведомлениях",
"text_023": "Не пытаться сразу подключаться к серверу и загружать сообщения для уведомлений. По умолчанию приложение пытается расшифровать текст на устройстве и показать его в уведомлении, в том числе на заблокированном экране. (Само сообщение, даже в зашифрованном виде, не передаётся через серверы push-уведомлений.)",
"text_024": "Не удалось сохранить настройку уведомлений"
"text_024": "Не удалось сохранить настройку уведомлений",
"text_025": "Проверить звук в браузере",
"text_026": "Проиграет короткий тестовый сигнал и проверит AudioContext",
"text_027": "Проверяем…",
"text_028": "Тестовый сигнал проигран. Если вы его не слышите, проверьте громкость и беззвучный режим устройства.",
"text_029": "Этот браузер не поддерживает AudioContext",
"text_030": "Браузер заблокировал AudioContext. Разрешите звук для этой страницы и нажмите кнопку ещё раз.",
"text_031": "Звук в открытом приложении выключен. Включите его переключателем выше и повторите проверку.",
"text_032": "Не удалось воспроизвести сигнал. Проверьте разрешение звука в браузере и системную громкость."
},
"solana_rpc_check_view": {
"text_001": "Проверка Solana RPC",
@@ -10,6 +10,7 @@ import {
} from '../services/dm-chat-prefs.js';
import { DEVICE_PREFS_EVENT, getDevicePref, setDevicePref } from '../services/device-prefs.js';
import { showToast } from '../services/channels-ux.js';
import { testDmSound } from '../services/dm-audio.js';
export const pageMeta = { id: 'notification-settings-view', get title() { return t('screens.notification_settings_view.text_001'); } };
@@ -47,6 +48,43 @@ export function render({ navigate, chrome } = {}) {
soundSwitch.addEventListener('change', () => setDevicePref('dmSound', soundSwitch.checked));
soundList.append(soundRow);
const soundTestRow = document.createElement('div');
soundTestRow.className = 'nav-row nav-row--action';
soundTestRow.innerHTML = `
<span class="nav-row__text">
<span class="nav-row__label"></span>
<span class="nav-row__hint"></span>
</span>
`;
soundTestRow.querySelector('.nav-row__label').textContent = t('screens.notification_settings_view.text_025');
soundTestRow.querySelector('.nav-row__hint').textContent = t('screens.notification_settings_view.text_026');
const soundTestButton = document.createElement('button');
soundTestButton.type = 'button';
soundTestButton.className = 'primary-btn nav-row__button';
soundTestButton.textContent = t('screens.notification_settings_view.text_025');
soundTestButton.addEventListener('click', async () => {
soundTestButton.disabled = true;
soundTestButton.textContent = t('screens.notification_settings_view.text_027');
try {
const result = await testDmSound();
const message = {
played: t('screens.notification_settings_view.text_028'),
unsupported: t('screens.notification_settings_view.text_029'),
blocked: t('screens.notification_settings_view.text_030'),
disabled: t('screens.notification_settings_view.text_031'),
error: t('screens.notification_settings_view.text_032'),
}[result.code] || t('screens.notification_settings_view.text_032');
showToast(message, { kind: result.ok ? 'success' : 'error' });
} finally {
if (!disposed) {
soundTestButton.disabled = false;
soundTestButton.textContent = t('screens.notification_settings_view.text_025');
}
}
});
soundTestRow.append(soundTestButton);
soundList.append(soundTestRow);
// Системные уведомления – когда приложение свёрнуто или закрыто.
const systemList = document.createElement('div');
systemList.className = 'nav-list';
+70
View File
@@ -0,0 +1,70 @@
import { getDevicePref } from './device-prefs.js';
let audioContext = null;
let audioUnlocked = false;
function audioContextConstructor() {
return globalThis.window?.AudioContext || globalThis.window?.webkitAudioContext || null;
}
export async function unlockDmAudio() {
const AudioContextConstructor = audioContextConstructor();
if (!AudioContextConstructor) return { ok: false, code: 'unsupported' };
try {
if (!audioContext) audioContext = new AudioContextConstructor();
if (audioContext.state === 'suspended') await audioContext.resume();
audioUnlocked = audioContext.state === 'running';
return audioUnlocked
? { ok: true, code: 'ready', state: audioContext.state }
: { ok: false, code: 'blocked', state: audioContext.state };
} catch (error) {
return { ok: false, code: 'error', state: audioContext?.state || 'unknown', error };
}
}
function playSignal({ extended = false } = {}) {
if (!audioUnlocked || !audioContext || audioContext.state !== 'running') {
return { ok: false, code: 'blocked', state: audioContext?.state || 'unknown' };
}
try {
const now = audioContext.currentTime;
const gain = audioContext.createGain();
gain.connect(audioContext.destination);
gain.gain.setValueAtTime(0.0001, now);
const pulse = (offsetSec, freqHz, durationSec, peakGain) => {
const osc = audioContext.createOscillator();
osc.type = 'sine';
osc.frequency.setValueAtTime(freqHz, now + offsetSec);
osc.connect(gain);
gain.gain.exponentialRampToValueAtTime(peakGain, now + offsetSec + 0.01);
gain.gain.exponentialRampToValueAtTime(0.0001, now + offsetSec + durationSec);
osc.start(now + offsetSec);
osc.stop(now + offsetSec + durationSec + 0.02);
};
if (extended) {
pulse(0, 880, 0.18, 0.032);
pulse(0.24, 1174, 0.2, 0.026);
pulse(0.52, 1567, 0.24, 0.02);
} else {
pulse(0, 1046, 0.12, 0.028);
pulse(0.17, 1318, 0.14, 0.022);
}
return { ok: true, code: 'played', state: audioContext.state };
} catch (error) {
return { ok: false, code: 'error', state: audioContext.state, error };
}
}
export async function playDmSignal(options = {}) {
if (getDevicePref('dmSound', true) === false) return { ok: false, code: 'disabled' };
const unlocked = await unlockDmAudio();
return unlocked.ok ? playSignal(options) : unlocked;
}
export async function testDmSound() {
const unlocked = await unlockDmAudio();
if (!unlocked.ok) return unlocked;
return playSignal({ extended: false });
}