Skip to content

Commit

Permalink
通知音などの発音方法を変え、iOSで音声出力が競合しないようにする (#12339)
Browse files Browse the repository at this point in the history
* HTMLAudioElementを使わないようにする

* fix CHANGELOG.md

---------

Co-authored-by: osamu <46447427+sam-osamu@users.noreply.github.com>
  • Loading branch information
samunohito and samunohito committed Nov 15, 2023
1 parent ca81f0d commit 38d6580
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
- Fix: 非ログイン時に「メモを追加」を表示しないように変更 #12309
- Fix: 絵文字ピッカーでの検索が更新されない問題を修正
- Fix: 特定の条件下でノートがnyaizeされない問題を修正
- Fix: iOSでの音声出力不備を改善 #12339

### Server
- Fix: トークンのないプラグインをアンインストールするときにエラーが出ないように
Expand Down
39 changes: 27 additions & 12 deletions packages/frontend/src/scripts/sound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

import { defaultStore } from '@/store.js';

const cache = new Map<string, HTMLAudioElement>();
const ctx = new AudioContext();
const cache = new Map<string, AudioBuffer>();

export const soundsTypes = [
null,
Expand Down Expand Up @@ -60,15 +61,20 @@ export const soundsTypes = [
'noizenecio/kick_gaba7',
] as const;

export function getAudio(file: string, useCache = true): HTMLAudioElement {
let audio: HTMLAudioElement;
export async function getAudio(file: string, useCache = true) {
if (useCache && cache.has(file)) {
audio = cache.get(file);
} else {
audio = new Audio(`/client-assets/sounds/${file}.mp3`);
if (useCache) cache.set(file, audio);
return cache.get(file)!;
}
return audio;

const response = await fetch(`/client-assets/sounds/${file}.mp3`);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await ctx.decodeAudioData(arrayBuffer);

if (useCache) {
cache.set(file, audioBuffer);
}

return audioBuffer;
}

export function setVolume(audio: HTMLAudioElement, volume: number): HTMLAudioElement {
Expand All @@ -84,8 +90,17 @@ export function play(type: 'noteMy' | 'note' | 'antenna' | 'channel' | 'notifica
playFile(sound.type, sound.volume);
}

export function playFile(file: string, volume: number) {
const audio = setVolume(getAudio(file), volume);
if (audio.volume === 0) return;
audio.play();
export async function playFile(file: string, volume: number) {
const masterVolume = defaultStore.state.sound_masterVolume;
if (masterVolume === 0 || volume === 0) {
return;
}

const gainNode = ctx.createGain();
gainNode.gain.value = masterVolume * volume;

const soundSource = ctx.createBufferSource();
soundSource.buffer = await getAudio(file);
soundSource.connect(gainNode).connect(ctx.destination);
soundSource.start();
}

0 comments on commit 38d6580

Please sign in to comment.