Skip to content

Commit

Permalink
fix: volume control not working on MacOS
Browse files Browse the repository at this point in the history
  • Loading branch information
Blackman99 committed Jun 5, 2023
1 parent f272022 commit ad9254e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
23 changes: 22 additions & 1 deletion src/lib/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ export const duration = writable(0)
export const isDark = writable(localStorage.getItem(COLOR_MODE_KEY) === 'on')
export const inWindow = writable(true)

export const audioCtx: {
ctx?: AudioContext
source?: MediaElementAudioSourceNode
} = {
ctx: undefined,
source: undefined,
}

export const displayPlayedSeconds = derived(playedSeconds, $playedSeconds => {
const minutes = Math.floor($playedSeconds / 60)
const secondsRemain = $playedSeconds % 60
Expand Down Expand Up @@ -117,6 +125,8 @@ totalSongsNumber.subscribe(() => paginateSelectedPlaylistSongs())

const isFirst = writable(true)

let gainNode: GainNode

const createAudio = (src: string) => {
const audio = new Audio(src)
audio.volume = get(volume)
Expand Down Expand Up @@ -150,6 +160,13 @@ const createAudio = (src: string) => {
duration.set(audio.duration)
})

audioCtx.ctx = new window.AudioContext()
audioCtx.source = audioCtx.ctx.createMediaElementSource(audio)
gainNode = audioCtx.ctx.createGain()

audioCtx.source.connect(gainNode)
gainNode.connect(audioCtx.ctx.destination)

return audio
}

Expand All @@ -171,5 +188,9 @@ playingSong.subscribe(ps => {

volume.subscribe(vl => {
const audio = get(audioDom)
if (audio) audio.volume = Number(vl.toFixed(2))
if (audio)
audio.volume = vl

if (gainNode)
gainNode.gain.value = vl
})
13 changes: 8 additions & 5 deletions src/lib/utils/visualizer.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
const createVisualizer = (canvas: HTMLCanvasElement, audio: HTMLAudioElement) => {
import { audioCtx } from '$lib/store'

const createVisualizer = (canvas: HTMLCanvasElement) => {
const audioSource = audioCtx.source
const audioContext = audioCtx.ctx
if (!audioSource || !audioContext) return
let x = 0
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
const audioCtx = new window.AudioContext()
const audioSource = audioCtx.createMediaElementSource(audio)
const analyser = audioCtx.createAnalyser()
const analyser = audioContext.createAnalyser()
audioSource.connect(analyser)
analyser.connect(audioCtx.destination)
analyser.connect(audioContext.destination)
analyser.fftSize = 128
const bufferLength = analyser.frequencyBinCount
const dataArray = new Uint8Array(bufferLength)
Expand Down

0 comments on commit ad9254e

Please sign in to comment.