Skip to content

Commit 3240bfb

Browse files
committed
move useAudioPlayer into AudioProvider
1 parent 22b00d2 commit 3240bfb

File tree

6 files changed

+96
-113
lines changed

6 files changed

+96
-113
lines changed

src/__generated__/gatsby-types.ts

+44-29
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/components/AudioPlayer/Audio.tsx

-6
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
import React from 'react'
2-
import useAudioPlayer from 'src/hooks/useAudioPlayer'
32
import AudioControls from 'src/components/AudioPlayer/AudioControls'
43
import AudioInfo from 'src/components/AudioPlayer/AudioInfo'
54
import AudioVolume from 'src/components/AudioPlayer/AudioVolume'
65
import AudioModal from 'src/components/AudioPlayer/AudioModal'
76
import { m as motion, AnimatePresence } from 'framer-motion'
8-
import { AudioContext } from 'src/components/AudioPlayer/AudioProvider'
9-
import { useContextSelector } from 'use-context-selector'
107

118
import { useAtom } from "jotai"
129
import {
@@ -57,9 +54,6 @@ const AudioPlayer: React.FC = () => {
5754
-webkit-gradient(linear, 0% 0%, 100% 0%, color-stop(${currentPercentage}, #fff), color-stop(${currentPercentage}, #414141))
5855
`
5956

60-
const audio = useContextSelector(AudioContext, audio => audio)
61-
useAudioPlayer(audio)
62-
6357
return (
6458
<AnimatePresence>
6559
{isAudioMiniPlayerOpen ? isAudioModalOpen

src/components/AudioPlayer/AudioProvider.tsx

+4-22
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,11 @@
1-
import React, { useRef, useEffect, ReactNode } from 'react'
2-
import { useStaticQuery, graphql } from 'gatsby'
3-
1+
import React, { ReactNode } from 'react'
2+
import useAudioPlayer from 'src/hooks/useAudioPlayer'
43
import { createContext } from 'use-context-selector'
54

6-
export const AudioContext = createContext<React.MutableRefObject<HTMLAudioElement>|null>(null!)
5+
export const AudioContext = createContext<React.MutableRefObject<HTMLAudioElement>>(null!)
76

87
export const AudioProvider = ({ children }: { children: ReactNode }) => {
9-
const { audio } = useStaticQuery(
10-
graphql`
11-
query {
12-
audio: allFile(filter: {id: {eq: "e8d9270b-16a0-5bdb-b214-c2aff1bb7160"}}) {
13-
edges {
14-
node {
15-
publicURL
16-
}
17-
}
18-
}
19-
}
20-
`
21-
)
22-
23-
let audioRef: React.MutableRefObject<HTMLAudioElement> | null = null
24-
useEffect(() => {
25-
audioRef = useRef<HTMLAudioElement>(new Audio(audio.edges[0].node.publicURL))
26-
}, [])
8+
const { audioRef } = useAudioPlayer()
279

2810
return (
2911
<AudioContext.Provider value={audioRef}>

src/hooks/useAudioPlayer.ts

+43-54
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
currentTimeAtom,
1717
} from 'src/atoms/track'
1818

19-
function useAudioPlayer(audioRef: React.MutableRefObject<HTMLAudioElement>|null) {
19+
function useAudioPlayer() {
2020
const [tracks] = useAtom(tracksAtom)
2121
const resetTracks = useResetAtom(tracksAtom)
2222
const [, toPrevTrack] = useAtom(prevTrackAtom)
@@ -30,6 +30,7 @@ function useAudioPlayer(audioRef: React.MutableRefObject<HTMLAudioElement>|null)
3030
const [skipTime, setSkipTime] = useAtom(skipTimeAtom)
3131
const [currentTime] = useAtom(currentTimeAtom)
3232

33+
const audioRef = useRef<HTMLAudioElement>(null!)
3334
const isReady = useRef(false)
3435

3536
const setMediaMetadata = (audioTracks: Track[]) => {
@@ -109,17 +110,19 @@ function useAudioPlayer(audioRef: React.MutableRefObject<HTMLAudioElement>|null)
109110
updatePositionState()
110111
}
111112
})
112-
navigator.mediaSession.setActionHandler('previoustrack', () => toPrevTrack(audioRef?.current))
113+
navigator.mediaSession.setActionHandler('previoustrack', () => toPrevTrack(audioRef.current))
113114
navigator.mediaSession.setActionHandler('nexttrack', () => toNextTrack())
114115
}
115116
}
116117

117-
const onScrub = (value: string) => {
118-
if (audioRef?.current) {
119-
audioRef.current.currentTime = parseInt(value, 10)
120-
setTrackProgress(audioRef.current.currentTime)
121-
}
122-
}
118+
useEffect(() => {
119+
// initialize audioRef
120+
audioRef.current = new Audio('/001.wav')
121+
return (() => {
122+
// prevent memory leak
123+
audioRef.current.pause()
124+
})
125+
}, [])
123126

124127
// updatePositionState https://developer.mozilla.org/en-US/docs/Web/API/MediaSession/setPositionState
125128
useEffect(() => {
@@ -136,74 +139,61 @@ function useAudioPlayer(audioRef: React.MutableRefObject<HTMLAudioElement>|null)
136139
}, [duration, playbackRate, trackProgress])
137140

138141
useEffect(() => {
139-
if (audioRef?.current) {
140-
audioRef.current.volume = volume
141-
}
142+
audioRef.current.volume = volume
142143
}, [volume])
143144

144145
useEffect(() => {
145-
if (audioRef?.current) {
146-
audioRef.current.muted = isMute
147-
}
146+
audioRef.current.muted = isMute
148147
}, [isMute])
149148

150149
useEffect(() => {
151-
if (audioRef?.current) {
152-
audioRef.current.currentTime = currentTime
153-
setTrackProgress(audioRef.current.currentTime)
154-
}
150+
audioRef.current.currentTime = currentTime
151+
setTrackProgress(audioRef.current.currentTime)
155152
}, [currentTime])
156153

157154
useEffect(() => {
158-
if (audioRef?.current) {
159-
// seekforward
160-
if (skipTime > 0) {
161-
audioRef.current.currentTime = Math.min(audioRef.current.currentTime + skipTime, audioRef.current.duration)
162-
//seekbackward
163-
} else if (skipTime < 0) {
164-
audioRef.current.currentTime = Math.max(audioRef.current.currentTime + skipTime, 0)
165-
} else {
166-
return
167-
}
168-
setTrackProgress(audioRef.current.currentTime)
169-
updatePositionState()
170-
setSkipTime(0)
155+
// seekforward
156+
if (skipTime > 0) {
157+
audioRef.current.currentTime = Math.min(audioRef.current.currentTime + skipTime, audioRef.current.duration)
158+
//seekbackward
159+
} else if (skipTime < 0) {
160+
audioRef.current.currentTime = Math.max(audioRef.current.currentTime + skipTime, 0)
161+
} else {
162+
return
171163
}
164+
setTrackProgress(audioRef.current.currentTime)
165+
updatePositionState()
166+
setSkipTime(0)
172167
}, [skipTime])
173168

174169
useEffect(() => {
175170
if (isPlaying) {
176-
audioRef?.current?.play().then(_ => {
177-
if (audioRef.current) {
178-
setDuration(audioRef.current.duration)
179-
setActionHandler()
180-
}
171+
audioRef.current.play().then(_ => {
172+
setDuration(audioRef.current.duration)
173+
setActionHandler()
181174
})
182175
} else {
183-
audioRef?.current?.pause()
176+
audioRef.current.pause()
184177
}
185178
}, [isPlaying])
186179

187180
// Handles cleanup and setup when changing tracks
188181
useEffect(() => {
189-
audioRef?.current?.pause()
182+
audioRef.current.pause()
190183

191184
if (tracks[0] && isReady.current) {
192185
// remove previous audio eventlisners
193-
if(audioRef?.current) {
194-
audioRef.current.removeEventListener('timeupdate', (_event) => {
195-
if (audioRef.current?.ended) {
196-
toNextTrack()
197-
} else if (audioRef.current) {
198-
setTrackProgress(audioRef.current.currentTime)
199-
}
200-
})
201-
}
202-
if (audioRef) {
203-
audioRef.current = new Audio(tracks[0].audioSrc)
204-
}
186+
audioRef.current.removeEventListener('timeupdate', (_event) => {
187+
if (audioRef.current.ended) {
188+
toNextTrack()
189+
} else {
190+
setTrackProgress(audioRef.current.currentTime)
191+
}
192+
})
193+
194+
audioRef.current = new Audio(tracks[0].audioSrc)
205195
// https://developer.mozilla.org/en-US/docs/Web/API/MediaMetadata
206-
audioRef?.current.play().then(_ => {
196+
audioRef.current.play().then(_ => {
207197
if (audioRef.current) {
208198
setDuration(audioRef.current.duration)
209199
setTrackProgress(audioRef.current.currentTime)
@@ -212,8 +202,8 @@ function useAudioPlayer(audioRef: React.MutableRefObject<HTMLAudioElement>|null)
212202
setIsPlaying(true)
213203
}
214204
})
215-
audioRef?.current.addEventListener('timeupdate', (_event) => {
216-
if (audioRef.current?.ended) {
205+
audioRef.current.addEventListener('timeupdate', (_event) => {
206+
if (audioRef.current.ended) {
217207
toNextTrack()
218208
} else if (audioRef.current) {
219209
setTrackProgress(audioRef.current.currentTime)
@@ -227,7 +217,6 @@ function useAudioPlayer(audioRef: React.MutableRefObject<HTMLAudioElement>|null)
227217

228218
return {
229219
audioRef,
230-
onScrub,
231220
}
232221
}
233222

src/pages/playlist/{ContentfulPlaylist.slug}.tsx

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useEffect } from 'react'
1+
import React, { useState } from 'react'
22
import { PageProps, graphql } from 'gatsby'
33

44
//Components
@@ -19,6 +19,8 @@ const PlaylistPage: React.FC<PageProps<GatsbyTypes.PlaylistQuery>> = ({ data, lo
1919
const [,updateTracks] = useAtom(updateTracksAtom)
2020
const [,setHistory] = useAtom(historyAtom)
2121

22+
const [isPlayed, setIsPlayed] = useState(false)
23+
2224
const audio = useContextSelector(AudioContext, audio => audio)
2325

2426
const playlist = data.contentfulPlaylist
@@ -67,6 +69,7 @@ const PlaylistPage: React.FC<PageProps<GatsbyTypes.PlaylistQuery>> = ({ data, lo
6769
audio.current.pause()
6870
audio.current.muted = false
6971
audio.current.currentTime = 0
72+
setIsPlayed(true)
7073
}
7174
}
7275

@@ -127,7 +130,7 @@ const PlaylistPage: React.FC<PageProps<GatsbyTypes.PlaylistQuery>> = ({ data, lo
127130
<button
128131
className="flex items-center"
129132
onClick={() => {
130-
initializeForSafari()
133+
if (!isPlayed) initializeForSafari()
131134
updateTracks(normarizedSongs.slice(index))
132135
setHistory(normarizedSongs.slice(0, index))
133136
}}
File renamed without changes.

0 commit comments

Comments
 (0)