Skip to content

Commit

Permalink
playback!
Browse files Browse the repository at this point in the history
  • Loading branch information
SheepTester committed May 2, 2024
1 parent 1b9ad89 commit f210e98
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 6 deletions.
42 changes: 37 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import { TextArea } from './components/TextArea'
import { PlayIcon } from './components/PlayIcon'
import { PauseIcon } from './components/PauseIcon'
import { Part, strategize } from './video-strategy'
import { useNow } from './useNow'

type PlayState =
| { playing: false; time: number }
| { playing: true; offset: number }

export function App () {
const nextId = useRef(0)
Expand Down Expand Up @@ -35,10 +40,21 @@ export function App () {
content: 'Today we will talk about things.'
}
])
const [playing, setPlaying] = useState(false)
const [time, setTime] = useState(0)
const [playState, setPlayState] = useState<PlayState>({
playing: false,
time: 0
})

const now = useNow(playState.playing)
const previewVideo = useMemo(() => strategize(parts), [parts])

const time = Math.max(
Math.min(
playState.playing ? now + playState.offset : playState.time,
previewVideo.length
),
0
)
const caption = previewVideo.captions.findLast(
caption => time >= caption.time
) ?? { content: '' }
Expand All @@ -57,13 +73,29 @@ export function App () {
</div>
</div>
<div className='controls'>
<button className='play-btn' onClick={() => setPlaying(!playing)}>
{playing ? <PauseIcon /> : <PlayIcon />}
<button
className='play-btn'
onClick={() =>
setPlayState(
playState.playing
? { playing: false, time }
: { playing: true, offset: time - Date.now() }
)
}
>
{playState.playing ? <PauseIcon /> : <PlayIcon />}
</button>
<input
type='range'
value={time}
onChange={e => setTime(e.currentTarget.valueAsNumber)}
onChange={e => {
const time = e.currentTarget.valueAsNumber
setPlayState(
playState.playing
? { playing: true, offset: time - Date.now() }
: { playing: false, time }
)
}}
step='any'
min={0}
max={previewVideo.length}
Expand Down
2 changes: 1 addition & 1 deletion src/global.css
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ button:not(:disabled) {
left: 0;
right: 0;
bottom: 0;
margin: 10px;
margin: 15px;
text-align: center;
font-size: 12px;

Expand Down
21 changes: 21 additions & 0 deletions src/useNow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useEffect, useState } from 'react'

export function useNow (enable = true) {
const [now, setNow] = useState(0)

useEffect(() => {
let lastAnimationFrame = 0
if (enable) {
const check = () => {
setNow(Date.now())
lastAnimationFrame = window.requestAnimationFrame(check)
}
check()
}
return () => {
window.cancelAnimationFrame(lastAnimationFrame)
}
}, [enable])

return Date.now()
}

0 comments on commit f210e98

Please sign in to comment.