Commit 233bcb1f authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Make Discovery's mic listen continuous instead of a fixed 5-second clip

Press to start, press again to stop - identification is retried
periodically against the growing recording while listening, and
listening stops automatically the instant a match is found (matching
stops immediately to control API cost; it never keeps checking in the
background after success). Also renames the failure message to "We
could not detect this song".
parent ded2404d
{ {
"title": "Discovery", "title": "Discovery",
"aria.listenIdle": "Listen for what’s playing", "aria.listenIdle": "Listen for what’s playing",
"aria.listening": "Listening, {{countdown}} seconds left", "aria.listening": "Listening, {{elapsed}} seconds, tap to stop",
"status.listening": "Listening…", "status.listening": "Listening… tap to stop",
"status.identifying": "Identifying…", "status.identifying": "Identifying…",
"status.idleHint": "Tap to identify what's playing - listens for 5 seconds", "status.idleHint": "Tap to start listening - stops automatically once it finds a match",
"fileDrop.label": "Drop a short clip of what's playing to identify it", "fileDrop.label": "Drop a short clip of what's playing to identify it",
"message.detected": "Detected: {{title}} - {{artist}}", "message.detected": "Detected: {{title}} - {{artist}}",
"message.notIdentified": "Could not identify that clip.", "message.notIdentified": "Could not identify that clip.",
......
{ {
"title": "کشف", "title": "کشف",
"aria.listenIdle": "شنیدن آنچه پخش می‌شود", "aria.listenIdle": "شنیدن آنچه پخش می‌شود",
"aria.listening": "در حال شنیدن، {{countdown}} ثانیه باقی مانده", "aria.listening": "در حال شنیدن، {{elapsed}} ثانیه، برای توقف ضربه بزن",
"status.listening": "در حال شنیدن…", "status.listening": "در حال شنیدن… برای توقف ضربه بزن",
"status.identifying": "در حال شناسایی…", "status.identifying": "در حال شناسایی…",
"status.idleHint": "برای شناسایی آنچه پخش می‌شود ضربه بزن - به مدت ۵ ثانیه می‌شنود", "status.idleHint": "برای شروع شنیدن ضربه بزن - با پیدا شدن آهنگ خودکار متوقف می‌شود",
"fileDrop.label": "یک کلیپ کوتاه از آنچه پخش می‌شود رها کن تا شناسایی شود", "fileDrop.label": "یک کلیپ کوتاه از آنچه پخش می‌شود رها کن تا شناسایی شود",
"message.detected": "شناسایی شد: {{title}} - {{artist}}", "message.detected": "شناسایی شد: {{title}} - {{artist}}",
"message.notIdentified": "این کلیپ شناسایی نشد.", "message.notIdentified": "این کلیپ شناسایی نشد.",
......
...@@ -22,12 +22,13 @@ const SONG = { ...@@ -22,12 +22,13 @@ const SONG = {
library_song_id: null, library_song_id: null,
} }
/** Stands in for the real MediaRecorder - jsdom has no audio capture support at all, so this /** Stands in for the real MediaRecorder - jsdom has no audio capture support at all, so this is
* is what makes the "record 5 seconds automatically" flow testable without a browser. start() * what makes the "listen continuously, periodically re-check, stop on match" flow testable
* fires one synchronous data chunk (a real recorder would stream several over time, but the * without a browser. start() and requestData() both fire a synchronous data chunk (a real
* component only cares that *something* arrives before stop()); stop() is driven by the * recorder streams several over time and requestData() forces an early flush mid-recording -
* component's own countdown, not by the test calling it directly - mirrors how a real 5-second * the component only cares that *something* arrives each time); stop() is driven by the
* auto-stop actually happens. */ * component itself (either the periodic check finding a match, or the test calling the button
* again), never by a fixed timer the fake owns. */
class FakeMediaRecorder { class FakeMediaRecorder {
static isTypeSupported(type: string) { static isTypeSupported(type: string) {
return type === 'audio/webm' return type === 'audio/webm'
...@@ -41,6 +42,9 @@ class FakeMediaRecorder { ...@@ -41,6 +42,9 @@ class FakeMediaRecorder {
start() { start() {
this.ondataavailable?.({ data: new Blob(['fake-audio-bytes']) }) this.ondataavailable?.({ data: new Blob(['fake-audio-bytes']) })
} }
requestData() {
this.ondataavailable?.({ data: new Blob(['fake-audio-bytes']) })
}
stop() { stop() {
this.onstop?.() this.onstop?.()
} }
...@@ -114,7 +118,7 @@ describe('Discovery', () => { ...@@ -114,7 +118,7 @@ describe('Discovery', () => {
}) })
}) })
it('records 5 seconds automatically, shows a listening state, and submits the clip', async () => { it('listens continuously, periodically re-checks, and stops automatically once a match is found', async () => {
mockMicSupport() mockMicSupport()
const listenSpy = vi.spyOn(discoveryApi, 'listen').mockResolvedValue({ const listenSpy = vi.spyOn(discoveryApi, 'listen').mockResolvedValue({
status: 'success', status: 'success',
...@@ -127,7 +131,7 @@ describe('Discovery', () => { ...@@ -127,7 +131,7 @@ describe('Discovery', () => {
const button = await screen.findByLabelText(/Listen for what/) const button = await screen.findByLabelText(/Listen for what/)
// Fake timers have to be active *before* the click, since that's what starts the // Fake timers have to be active *before* the click, since that's what starts the
// component's countdown setInterval - switching to fake timers afterward wouldn't take // component's elapsed-time setInterval - switching to fake timers afterward wouldn't take
// over a real interval already running. fireEvent (not userEvent) deliberately - userEvent's // over a real interval already running. fireEvent (not userEvent) deliberately - userEvent's
// own internal delay handling doesn't play well with fake timers here, and a plain click // own internal delay handling doesn't play well with fake timers here, and a plain click
// event is all this needs: React calls the onClick handler synchronously either way. // event is all this needs: React calls the onClick handler synchronously either way.
...@@ -137,10 +141,18 @@ describe('Discovery', () => { ...@@ -137,10 +141,18 @@ describe('Discovery', () => {
fireEvent.click(button) fireEvent.click(button)
}) })
expect(screen.getByLabelText(/Listening, 5 seconds left/)).toBeInTheDocument() expect(screen.getByLabelText(/Listening, 0 seconds/)).toBeInTheDocument()
// No check yet before the first 5-second mark - still just recording.
await act(async () => { await act(async () => {
await vi.advanceTimersByTimeAsync(5000) await vi.advanceTimersByTimeAsync(4000)
})
expect(listenSpy).not.toHaveBeenCalled()
// The 5-second mark triggers the first periodic check, which this test's mock resolves
// as a match - recording should stop itself rather than waiting for a 6th second.
await act(async () => {
await vi.advanceTimersByTimeAsync(1000)
}) })
} finally { } finally {
vi.useRealTimers() vi.useRealTimers()
...@@ -158,6 +170,80 @@ describe('Discovery', () => { ...@@ -158,6 +170,80 @@ describe('Discovery', () => {
expect(await screen.findByLabelText(/Listen for what/)).toBeInTheDocument() expect(await screen.findByLabelText(/Listen for what/)).toBeInTheDocument()
}) })
it('keeps listening past a miss and only stops once a later check succeeds', async () => {
mockMicSupport()
const listenSpy = vi
.spyOn(discoveryApi, 'listen')
.mockResolvedValueOnce({ status: 'error', message: 'We could not detect this song' })
.mockResolvedValueOnce({
status: 'success',
detected: { title: 'Found Song', artist: 'Found Artist', confidence: null, source: null },
discovery_id: 42,
library_song_id: null,
})
renderDiscovery()
const button = await screen.findByLabelText(/Listen for what/)
vi.useFakeTimers()
try {
await act(async () => {
fireEvent.click(button)
})
// First check (5s) misses - the UI stays silent and keeps listening, not a disruptive
// "no match" message every cycle.
await act(async () => {
await vi.advanceTimersByTimeAsync(5000)
})
expect(listenSpy).toHaveBeenCalledTimes(1)
expect(screen.getByLabelText(/Listening,/)).toBeInTheDocument()
expect(screen.queryByText(/We could not detect this song/)).not.toBeInTheDocument()
// Second check (10s) finds it.
await act(async () => {
await vi.advanceTimersByTimeAsync(5000)
})
} finally {
vi.useRealTimers()
}
expect(listenSpy).toHaveBeenCalledTimes(2)
await waitFor(() => {
expect(screen.getByText('Detected: Found Song - Found Artist')).toBeInTheDocument()
})
})
it('stops immediately when the listen button is tapped again, and reports a miss', async () => {
mockMicSupport()
const listenSpy = vi.spyOn(discoveryApi, 'listen').mockResolvedValue({ status: 'error', message: 'We could not detect this song' })
renderDiscovery()
const startButton = await screen.findByLabelText(/Listen for what/)
vi.useFakeTimers()
try {
await act(async () => {
fireEvent.click(startButton)
})
await act(async () => {
await vi.advanceTimersByTimeAsync(2000)
})
// Manual stop before any periodic check has even fired (2s < the 5s interval) - this is
// the only identify call that happens, and since it misses, the user needs to actually be
// told (unlike a background miss while still recording).
const stopButton = screen.getByLabelText(/Listening,/)
await act(async () => {
fireEvent.click(stopButton)
})
} finally {
vi.useRealTimers()
}
expect(listenSpy).toHaveBeenCalledTimes(1)
expect(await screen.findByText('We could not detect this song')).toBeInTheDocument()
expect(await screen.findByLabelText(/Listen for what/)).toBeInTheDocument()
})
it('releases the microphone once recording stops', async () => { it('releases the microphone once recording stops', async () => {
const { stopTrack } = mockMicSupport() const { stopTrack } = mockMicSupport()
vi.spyOn(discoveryApi, 'listen').mockResolvedValue({ status: 'success', detected: { title: '', artist: '', confidence: null, source: null }, discovery_id: 1, library_song_id: null }) vi.spyOn(discoveryApi, 'listen').mockResolvedValue({ status: 'success', detected: { title: '', artist: '', confidence: null, source: null }, discovery_id: 1, library_song_id: null })
......
...@@ -11,10 +11,18 @@ function toPlayable(song: DiscoveredSong): PlayableSong { ...@@ -11,10 +11,18 @@ function toPlayable(song: DiscoveredSong): PlayableSong {
return { id: song.library_song_id!, title: song.title, artist: song.artist, coverart: song.coverart } return { id: song.library_song_id!, title: song.title, artist: song.artist, coverart: song.coverart }
} }
const LISTEN_SECONDS = 5 // Listening is now open-ended (tap to start, tap again to stop) rather than a fixed 5-second
// clip - a longer recording gives Shazam/AcoustID more material to match against, which is the
// whole point of letting it run. CHECK_INTERVAL_SECONDS controls how often the growing clip gets
// re-submitted for identification while still recording; the moment one of those checks finds a
// match, recording stops immediately - there's no value (and real API cost) in continuing to
// check after that. MAX_LISTEN_SECONDS is just a safety net against someone leaving the mic open
// indefinitely by accident, not a feature in itself.
const CHECK_INTERVAL_SECONDS = 5
const MAX_LISTEN_SECONDS = 60
// Real-time capture constraints, not post-processing - the browser's own audio pipeline // Real-time capture constraints, not post-processing - the browser's own audio pipeline
// applies these while recording, so they cost nothing on top of the fixed 5-second window. // applies these while recording, so they cost nothing on top of the recording itself.
// autoGainControl boosts a quiet/distant snippet ("sensitivity"); noiseSuppression removes // autoGainControl boosts a quiet/distant snippet ("sensitivity"); noiseSuppression removes
// steady background noise (traffic, HVAC, chatter) before it ever reaches the recorded clip. // steady background noise (traffic, HVAC, chatter) before it ever reaches the recorded clip.
// echoCancellation is explicitly off - it's built for cancelling a device's own call/speaker // echoCancellation is explicitly off - it's built for cancelling a device's own call/speaker
...@@ -48,13 +56,22 @@ export function Discovery() { ...@@ -48,13 +56,22 @@ export function Discovery() {
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<string | null>(null) const [message, setMessage] = useState<string | null>(null)
const [listening, setListening] = useState(false) const [listening, setListening] = useState(false)
const [countdown, setCountdown] = useState(LISTEN_SECONDS) const [elapsed, setElapsed] = useState(0)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer() const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const recorderRef = useRef<MediaRecorder | null>(null) const recorderRef = useRef<MediaRecorder | null>(null)
const streamRef = useRef<MediaStream | null>(null) const streamRef = useRef<MediaStream | null>(null)
const chunksRef = useRef<Blob[]>([]) const chunksRef = useRef<Blob[]>([])
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null) const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
// matchedRef short-circuits onstop once a periodic check already found the song (no second,
// redundant identify call); checkingRef prevents two identify requests overlapping if a check
// is still in flight when the next interval tick (or a manual stop) comes around;
// pendingCheckRef hands off from the interval tick (which only knows "it's time to check") to
// the recorder's own ondataavailable event (which is what actually has the freshly flushed
// audio data to check).
const matchedRef = useRef(false)
const checkingRef = useRef(false)
const pendingCheckRef = useRef(false)
function refresh() { function refresh() {
getDiscoveryHistory() getDiscoveryHistory()
...@@ -77,21 +94,38 @@ export function Discovery() { ...@@ -77,21 +94,38 @@ export function Discovery() {
// captured until the browser tab itself closes. // captured until the browser tab itself closes.
useEffect(() => stopStream, []) useEffect(() => stopStream, [])
async function handleListen(file: File) { function buildClipFile(mimeType: string): File {
const blob = new Blob(chunksRef.current, { type: mimeType })
return new File([blob], `clip.${extensionFor(mimeType)}`, { type: mimeType })
}
// isFinal distinguishes a background check (while still recording - stay silent on a miss,
// there'll be another chance in CHECK_INTERVAL_SECONDS) from the one made right as recording
// ends (manual stop or the safety cap - this is the last chance, so a miss has to actually
// tell the user rather than disappearing silently).
async function runIdentifyCheck(isFinal: boolean) {
if (checkingRef.current) return
checkingRef.current = true
if (isFinal) {
setBusy(true) setBusy(true)
setMessage(null) setMessage(null)
}
try { try {
const res = await listen(file) const mimeType = recorderRef.current?.mimeType || 'audio/webm'
const res = await listen(buildClipFile(mimeType))
if (res.status === 'success') { if (res.status === 'success') {
matchedRef.current = true
setMessage(t('message.detected', { title: res.detected.title ?? t('fallback.unknownTitle'), artist: res.detected.artist ?? '' })) setMessage(t('message.detected', { title: res.detected.title ?? t('fallback.unknownTitle'), artist: res.detected.artist ?? '' }))
refresh() refresh()
} else { recorderRef.current?.stop()
} else if (isFinal) {
setMessage(res.message) setMessage(res.message)
} }
} catch { } catch {
setMessage(t('message.notIdentified')) if (isFinal) setMessage(t('message.notIdentified'))
} finally { } finally {
setBusy(false) checkingRef.current = false
if (isFinal) setBusy(false)
} }
} }
...@@ -110,33 +144,67 @@ export function Discovery() { ...@@ -110,33 +144,67 @@ export function Discovery() {
const recorder = mimeType ? new MediaRecorder(stream, { mimeType }) : new MediaRecorder(stream) const recorder = mimeType ? new MediaRecorder(stream, { mimeType }) : new MediaRecorder(stream)
recorderRef.current = recorder recorderRef.current = recorder
chunksRef.current = [] chunksRef.current = []
matchedRef.current = false
checkingRef.current = false
pendingCheckRef.current = false
recorder.ondataavailable = (e) => { recorder.ondataavailable = (e) => {
if (e.data.size > 0) chunksRef.current.push(e.data) if (e.data.size > 0) chunksRef.current.push(e.data)
if (pendingCheckRef.current) {
pendingCheckRef.current = false
void runIdentifyCheck(false)
}
} }
recorder.onstop = () => { recorder.onstop = () => {
stopStream() stopStream()
setListening(false) setListening(false)
const type = recorder.mimeType || 'audio/webm' // Either a periodic check already found the match and is already showing its result, or
const blob = new Blob(chunksRef.current, { type }) // one is still in flight and will show its own result when it resolves - either way,
handleListen(new File([blob], `clip.${extensionFor(type)}`, { type })) // nothing left for this stop to do.
if (matchedRef.current || checkingRef.current) return
void runIdentifyCheck(true)
} }
recorder.start() recorder.start()
setListening(true) setListening(true)
setCountdown(LISTEN_SECONDS) setElapsed(0)
intervalRef.current = setInterval(() => { intervalRef.current = setInterval(() => {
setCountdown((prev) => { setElapsed((prev) => {
if (prev <= 1) { const next = prev + 1
recorder.stop() if (next >= MAX_LISTEN_SECONDS) {
return 0 recorderRef.current?.stop()
} else if (next % CHECK_INTERVAL_SECONDS === 0) {
pendingCheckRef.current = true
recorderRef.current?.requestData()
} }
return prev - 1 return next
}) })
}, 1000) }, 1000)
} }
function stopListening() {
recorderRef.current?.stop()
}
async function handleListen(file: File) {
setBusy(true)
setMessage(null)
try {
const res = await listen(file)
if (res.status === 'success') {
setMessage(t('message.detected', { title: res.detected.title ?? t('fallback.unknownTitle'), artist: res.detected.artist ?? '' }))
refresh()
} else {
setMessage(res.message)
}
} catch {
setMessage(t('message.notIdentified'))
} finally {
setBusy(false)
}
}
async function handleSwipe(songId: number, liked: boolean) { async function handleSwipe(songId: number, liked: boolean) {
await swipe(songId, liked) await swipe(songId, liked)
setHistory((h) => h.map((s) => (s.id === songId ? { ...s, liked } : s))) setHistory((h) => h.map((s) => (s.id === songId ? { ...s, liked } : s)))
...@@ -148,15 +216,19 @@ export function Discovery() { ...@@ -148,15 +216,19 @@ export function Discovery() {
<div className="mb-8 flex flex-col items-center gap-3 rounded-xl border border-outline-variant p-8 text-center"> <div className="mb-8 flex flex-col items-center gap-3 rounded-xl border border-outline-variant p-8 text-center">
<button <button
type="button" type="button"
onClick={startListening} onClick={listening ? stopListening : startListening}
disabled={listening || busy} disabled={busy}
aria-label={listening ? t('aria.listening', { countdown }) : t('aria.listenIdle')} aria-label={listening ? t('aria.listening', { elapsed }) : t('aria.listenIdle')}
className="relative flex h-20 w-20 items-center justify-center rounded-full transition-transform duration-150 active:scale-95 disabled:active:scale-100" className="relative flex h-20 w-20 items-center justify-center rounded-full transition-transform duration-150 active:scale-95 disabled:active:scale-100"
> >
{listening && ( {listening && (
<> <>
<span className="absolute inset-0 animate-ping rounded-full bg-primary/30" /> {/* Three copies of the same ripple, staggered - a new ring starts before the
<span className="absolute inset-0 rounded-full bg-primary/10" /> last one finishes fading, reading as continuous outward motion rather than
one static pulse (the old single animate-ping ring). */}
<span className="animate-listen-ring absolute inset-0 rounded-full bg-primary/40" />
<span className="animate-listen-ring absolute inset-0 rounded-full bg-primary/40" style={{ animationDelay: '0.6s' }} />
<span className="animate-listen-ring absolute inset-0 rounded-full bg-primary/40" style={{ animationDelay: '1.2s' }} />
</> </>
)} )}
<span <span
...@@ -166,7 +238,23 @@ export function Discovery() { ...@@ -166,7 +238,23 @@ export function Discovery() {
: 'border-outline-variant bg-surface-container text-on-surface-variant hover:border-outline-variant hover:text-on-surface' : 'border-outline-variant bg-surface-container text-on-surface-variant hover:border-outline-variant hover:text-on-surface'
}`} }`}
> >
{listening ? <span className="text-xl font-semibold tabular-nums">{countdown}</span> : <Ear size={26} strokeWidth={1.5} />} {listening ? (
<span className="flex flex-col items-center gap-1.5">
{/* A small live-looking equalizer rather than a bare number alone - each bar
has its own duration/delay so they never move in lockstep. Not a real
level meter (the mic input isn't analysed client-side), just ambient
motion that reads as "actively capturing sound". */}
<span className="flex h-3.5 items-end gap-0.5" aria-hidden="true">
<span className="animate-listen-bar h-full w-[3px] rounded-full bg-primary" style={{ animationDuration: '700ms' }} />
<span className="animate-listen-bar h-full w-[3px] rounded-full bg-primary" style={{ animationDuration: '920ms', animationDelay: '120ms' }} />
<span className="animate-listen-bar h-full w-[3px] rounded-full bg-primary" style={{ animationDuration: '640ms', animationDelay: '260ms' }} />
<span className="animate-listen-bar h-full w-[3px] rounded-full bg-primary" style={{ animationDuration: '860ms', animationDelay: '80ms' }} />
</span>
<span className="text-sm font-semibold tabular-nums">{elapsed}</span>
</span>
) : (
<Ear size={26} strokeWidth={1.5} />
)}
</span> </span>
</button> </button>
<span className="text-sm text-on-surface-variant"> <span className="text-sm text-on-surface-variant">
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment