fix timer

This commit is contained in:
2025-09-02 14:43:42 +02:00
parent b68c28a8d4
commit 6694425707
+115 -111
View File
@@ -1,20 +1,29 @@
import { useFocusEffect } from "@react-navigation/native";
import { useAudioPlayer } from "expo-audio";
import { CameraView, useCameraPermissions } from "expo-camera"; import { CameraView, useCameraPermissions } from "expo-camera";
import React from "react"; import React, { useCallback, useEffect, useRef, useState } from "react";
import { Text, View } from "react-native"; import { Text, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useSafeAreaInsets } from "react-native-safe-area-context";
import Svg, { Circle } from "react-native-svg";
import GradientButton from "../../components/GradientButton"; import GradientButton from "../../components/GradientButton";
import MusicLandHeader from "../../components/MusicLandHeader"; import MusicLandHeader from "../../components/MusicLandHeader";
import { increment, projectsRef } from "../../config/firebase";
import { Routes } from "../../navigation"; import { Routes } from "../../navigation";
import { goBack, navigate } from "../../navigation/NavigationService"; import { goBack, navigate } from "../../navigation/NavigationService";
import { gutters, Palette } from "../../styles"; import { gutters, Palette } from "../../styles";
import { FONT_FAMILY } from "../../styles/Fonts"; import { FONT_FAMILY } from "../../styles/Fonts";
import CreateLyricsHeader from "../Writing/components/CreateLyricsHeader"; import CreateLyricsHeader from "../Writing/components/CreateLyricsHeader";
// ADD: Firestore helpers to increment views
import { useFocusEffect } from "@react-navigation/native"; /**
import { useAudioPlayer } from "expo-audio"; * RecordPlayback — refactor robuste du compteur
import { useCallback, useEffect, useRef, useState } from "react"; *
import Svg, { Circle } from "react-native-svg"; * Correction de l'auto-start : on garde un flag countdownActiveRef pour
import { increment, projectsRef } from "../../config/firebase"; * empêcher l'effet de se déclencher tant que le timer n'a pas réellement démarré.
* On affiche 5→1 puis on bascule (pas de 0 visible) pour éviter le "bloqué sur 1".
*/
const TIME_BEFORE_INCREMENT_MS = 20000; // 20s
const RecordPlayback = ({ route }) => { const RecordPlayback = ({ route }) => {
const { top } = useSafeAreaInsets(); const { top } = useSafeAreaInsets();
const { project } = route.params || {}; const { project } = route.params || {};
@@ -25,13 +34,15 @@ const RecordPlayback = ({ route }) => {
// Refs // Refs
const cameraRef = useRef(null); const cameraRef = useRef(null);
const countdownTimerRef = useRef(null); const countdownTimerRef = useRef(null);
const listenTimerRef = useRef(null);
const checkSongEndRef = useRef(null);
const stopRequestedRef = useRef(false); const stopRequestedRef = useRef(false);
const startedRef = useRef(false); // empêche les doubles démarrages
const countdownActiveRef = useRef(false); // évite le déclenchement avant 1er tick
// Listen counter refs (inspired by MusicDetails) // Compteurs vues
const listenedMsRef = useRef(0); const listenedMsRef = useRef(0);
const incrementDoneRef = useRef(false); const incrementDoneRef = useRef(false);
const timerRef = useRef(null);
const timeBeforeIncrement = 20000; // 20 seconds
// UI / state // UI / state
const [isPreparing, setIsPreparing] = useState(false); const [isPreparing, setIsPreparing] = useState(false);
@@ -40,70 +51,74 @@ const RecordPlayback = ({ route }) => {
const [showProgress, setShowProgress] = useState(false); const [showProgress, setShowProgress] = useState(false);
const [progressInfo, setProgressInfo] = useState({ pos: 0, dur: 0 }); const [progressInfo, setProgressInfo] = useState({ pos: 0, dur: 0 });
// Derive song URL robustly // Musique
const songUrl = project?.songUrl || null; const songUrl = project?.songUrl || null;
const player = useAudioPlayer(songUrl ? { uri: songUrl } : undefined); const player = useAudioPlayer(songUrl ? { uri: songUrl } : undefined);
// useEffect(() => {
// setVideo(null);
// }, []);
useEffect(() => { useEffect(() => {
listenedMsRef.current = 0; listenedMsRef.current = 0;
incrementDoneRef.current = false; incrementDoneRef.current = false;
}, [songUrl]); }, [songUrl]);
// Poll player state to update progress ring // Poll player -> progress ring
useEffect(() => { useEffect(() => {
if (!player) return; if (!player) return;
const id = global.setInterval(() => { const id = setInterval(() => {
try { try {
const dur = (player?.duration || 0) * 1000; const dur = (player?.duration || 0) * 1000;
const pos = (player?.currentTime || 0) * 1000; const pos = (player?.currentTime || 0) * 1000;
setProgressInfo({ pos, dur }); setProgressInfo({ pos, dur });
} catch (_) {} } catch (_) {}
}, 250); }, 250);
return () => global.clearInterval(id); return () => clearInterval(id);
}, [player]); }, [player]);
// Permissions au mount + cleanup
useEffect(() => { useEffect(() => {
// Request permissions on mount if not granted
(async () => { (async () => {
try { try {
if (!cameraPermission?.granted) await requestCameraPermission(); if (!cameraPermission?.granted) await requestCameraPermission();
} catch (_) {} } catch (_) {}
})(); })();
return () => { return () => {
// Cleanup timers on unmount
try { try {
if (countdownTimerRef.current) { if (countdownTimerRef.current) clearInterval(countdownTimerRef.current);
global.clearInterval(countdownTimerRef.current); if (listenTimerRef.current) clearInterval(listenTimerRef.current);
if (checkSongEndRef.current) clearInterval(checkSongEndRef.current);
countdownTimerRef.current = null; countdownTimerRef.current = null;
} listenTimerRef.current = null;
if (timerRef.current) { checkSongEndRef.current = null;
global.clearInterval(timerRef.current);
timerRef.current = null;
}
} catch (_) {} } catch (_) {}
}; };
}, []); }, []); // eslint-disable-line react-hooks/exhaustive-deps
// Fully reset audio and recording state (used on focus and before new session) // Reset complet
const resetSession = useCallback(async () => { const resetSession = useCallback(async () => {
try { try {
if (countdownTimerRef.current) { if (countdownTimerRef.current) {
global.clearInterval(countdownTimerRef.current); clearInterval(countdownTimerRef.current);
countdownTimerRef.current = null; countdownTimerRef.current = null;
} }
if (timerRef.current) { if (listenTimerRef.current) {
global.clearInterval(timerRef.current); clearInterval(listenTimerRef.current);
timerRef.current = null; listenTimerRef.current = null;
} }
if (checkSongEndRef.current) {
clearInterval(checkSongEndRef.current);
checkSongEndRef.current = null;
}
startedRef.current = false;
stopRequestedRef.current = false; stopRequestedRef.current = false;
countdownActiveRef.current = false;
listenedMsRef.current = 0; listenedMsRef.current = 0;
incrementDoneRef.current = false; incrementDoneRef.current = false;
setIsPreparing(false); setIsPreparing(false);
setIsRecording(false); setIsRecording(false);
setShowProgress(false); setShowProgress(false);
setCountdown(0); setCountdown(0);
if (player) { if (player) {
try { try {
if (player.playing) await player.pause?.(); if (player.playing) await player.pause?.();
@@ -113,7 +128,6 @@ const RecordPlayback = ({ route }) => {
} catch (_) {} } catch (_) {}
}, [player]); }, [player]);
// Reset when screen gains focus (coming from "Recommencer", etc.)
useFocusEffect( useFocusEffect(
useCallback(() => { useCallback(() => {
void resetSession(); void resetSession();
@@ -121,64 +135,59 @@ const RecordPlayback = ({ route }) => {
}, [resetSession]) }, [resetSession])
); );
// Lancer le compte à rebours (le tick décrémente uniquement)
const startCountdownThenRecord = async () => { const startCountdownThenRecord = async () => {
console.log("start countdown");
if (!songUrl) return; if (!songUrl) return;
console.log("songUrl exists");
// Ensure clean state and audio at t=0
await resetSession(); await resetSession();
setIsPreparing(true); setIsPreparing(true);
setCountdown(5);
setShowProgress(false); setShowProgress(false);
setCountdown(5);
// Start countdown display; start recording+music WHEN countdown reaches 0 // On démarre l'intervalle puis on active le flag
if (countdownTimerRef.current) { if (countdownTimerRef.current) {
global.clearInterval(countdownTimerRef.current); clearInterval(countdownTimerRef.current);
countdownTimerRef.current = null; countdownTimerRef.current = null;
} }
countdownTimerRef.current = global.setInterval(() => { countdownTimerRef.current = setInterval(() => {
setCountdown((c) => { setCountdown((c) => Math.max(0, c - 1));
const next = (c || 0) - 1; }, 1000);
if (next <= 0) { countdownActiveRef.current = true;
console.log("clear timer"); };
// clear timer
global.clearInterval(countdownTimerRef.current); // Quand le compteur a réellement démarré ET atteint 0, on démarre
useEffect(() => {
if (!isPreparing) return;
if (!countdownActiveRef.current) return; // évite l'auto-start
if (countdown === 0 && !startedRef.current) {
startedRef.current = true;
if (countdownTimerRef.current) {
clearInterval(countdownTimerRef.current);
countdownTimerRef.current = null; countdownTimerRef.current = null;
// Ensure countdown overlay disappears and progress shows immediately }
countdownActiveRef.current = false;
// Bascule après rendu de la frame courante
requestAnimationFrame(() => {
setIsPreparing(false); setIsPreparing(false);
setShowProgress(true); setShowProgress(true);
// also set countdown to 0 explicitly in case of frame drop
if (c !== 0) {
// guard against stale value
setCountdown(0);
}
// start recording + music at the same time
void startRecordingWithMusic(); void startRecordingWithMusic();
}
return Math.max(0, next);
}); });
}, 1000); }
}; }, [countdown, isPreparing]);
const startRecordingWithMusic = async () => { const startRecordingWithMusic = async () => {
try { try {
stopRequestedRef.current = false; stopRequestedRef.current = false;
// Reset listen counters for this track/session
listenedMsRef.current = 0; listenedMsRef.current = 0;
incrementDoneRef.current = false; incrementDoneRef.current = false;
// Start recording
setIsRecording(true); setIsRecording(true);
setCountdown(0);
setIsPreparing(false);
setShowProgress(true); setShowProgress(true);
const recordPromise = cameraRef.current?.recordAsync?.({ const recordPromise = cameraRef.current?.recordAsync?.({
mute: true, mute: true,
maxDuration: 600, // safety cap (10 min) maxDuration: 600,
}); });
// Start playing with useAudioPlayer (like MusicDetails)
if (player && songUrl) { if (player && songUrl) {
try { try {
await player.seekTo?.(0); await player.seekTo?.(0);
@@ -186,15 +195,15 @@ const RecordPlayback = ({ route }) => {
await player.play?.(); await player.play?.();
} }
// Start timer to track listening time and increment views (like MusicDetails) // Incrément des vues
if (!timerRef.current && project?.id) { if (!listenTimerRef.current && project?.id) {
timerRef.current = global.setInterval(async () => { listenTimerRef.current = setInterval(async () => {
try { try {
if (player?.playing) { if (player?.playing) {
listenedMsRef.current += 500; listenedMsRef.current += 500;
if ( if (
!incrementDoneRef.current && !incrementDoneRef.current &&
listenedMsRef.current >= timeBeforeIncrement listenedMsRef.current >= TIME_BEFORE_INCREMENT_MS
) { ) {
incrementDoneRef.current = true; incrementDoneRef.current = true;
try { try {
@@ -208,61 +217,62 @@ const RecordPlayback = ({ route }) => {
}, 500); }, 500);
} }
// Monitor when song ends to stop recording // Fin du morceau -> stop recording
const checkSongEnd = global.setInterval(async () => { if (!checkSongEndRef.current) {
checkSongEndRef.current = setInterval(() => {
try { try {
if (player && !player.playing && !stopRequestedRef.current) { if (!player) return;
const duration = (player?.duration || 0) * 1000; const duration = (player?.duration || 0) * 1000;
const currentTime = (player?.currentTime || 0) * 1000; const currentTime = (player?.currentTime || 0) * 1000;
if (
// If we're near the end or stopped, stop recording (!player.playing && !stopRequestedRef.current) ||
if (duration > 0 && currentTime >= duration - 1000) { (duration > 0 && currentTime >= duration - 600)
) {
stopRequestedRef.current = true; stopRequestedRef.current = true;
global.clearInterval(checkSongEnd); if (checkSongEndRef.current) {
clearInterval(checkSongEndRef.current);
checkSongEndRef.current = null;
}
try { try {
cameraRef.current?.stopRecording?.(); cameraRef.current?.stopRecording?.();
} catch (_) {} } catch (_) {}
} }
}
} catch (_) {} } catch (_) {}
}, 1000); }, 500);
}
// Wait for recording to stop
const video = await recordPromise; const video = await recordPromise;
global.clearInterval(checkSongEnd);
// Stop audio if (checkSongEndRef.current) {
clearInterval(checkSongEndRef.current);
checkSongEndRef.current = null;
}
try { try {
if (player?.playing) { if (player?.playing) await player.pause?.();
await player.pause?.();
}
} catch (_) {} } catch (_) {}
if (listenTimerRef.current) {
// Clear listen timer after recording ends clearInterval(listenTimerRef.current);
if (timerRef.current) { listenTimerRef.current = null;
global.clearInterval(timerRef.current);
timerRef.current = null;
} }
setIsRecording(false); setIsRecording(false);
setIsPreparing(false);
setShowProgress(false); setShowProgress(false);
// Navigate to next screen with video uri if available if (video?.uri)
if (video?.uri) {
navigate(Routes.RecordedPlayback, { videoUri: video.uri, project }); navigate(Routes.RecordedPlayback, { videoUri: video.uri, project });
} else { else navigate(Routes.RecordedPlayback, { project });
navigate(Routes.RecordedPlayback, { project });
}
} catch (e) { } catch (e) {
// Fallback on error console.log("RecordPlayback error:", e);
console.log("error : ", e);
setIsRecording(false); setIsRecording(false);
setIsPreparing(false); setIsPreparing(false);
setShowProgress(false); setShowProgress(false);
if (timerRef.current) { if (listenTimerRef.current) {
global.clearInterval(timerRef.current); clearInterval(listenTimerRef.current);
timerRef.current = null; listenTimerRef.current = null;
}
if (checkSongEndRef.current) {
clearInterval(checkSongEndRef.current);
checkSongEndRef.current = null;
} }
} }
}; };
@@ -286,6 +296,7 @@ const RecordPlayback = ({ route }) => {
}} }}
> >
<MusicLandHeader progress={9} onPressBack={goBack} /> <MusicLandHeader progress={9} onPressBack={goBack} />
<View style={{ flex: 1, marginTop: 11 }}> <View style={{ flex: 1, marginTop: 11 }}>
<CreateLyricsHeader> <CreateLyricsHeader>
<Text <Text
@@ -300,8 +311,8 @@ const RecordPlayback = ({ route }) => {
</Text> </Text>
</CreateLyricsHeader> </CreateLyricsHeader>
{/* Centered countdown overlay */} {/* Overlay de compte à rebours : on affiche 5→1 pour éviter l'effet visuel à 1 */}
{isPreparing && countdown > 0 && !showProgress && ( {isPreparing && countdown >= 1 && !showProgress && (
<View <View
style={{ style={{
position: "absolute", position: "absolute",
@@ -353,16 +364,13 @@ const RecordPlayback = ({ route }) => {
{permissionsGranted && !isPreparing && !isRecording && ( {permissionsGranted && !isPreparing && !isRecording && (
<GradientButton <GradientButton
title="Lancer ma musique" title="Lancer ma musique"
containerStyle={{ containerStyle={{ width: "80%", alignSelf: "center" }}
width: "80%",
alignSelf: "center",
}}
disabled={!songUrl} disabled={!songUrl}
onPress={startCountdownThenRecord} onPress={startCountdownThenRecord}
/> />
)} )}
{/* Circular progress when countdown finished / recording */} {/* Progress circulaire */}
{permissionsGranted && (isRecording || showProgress) && ( {permissionsGranted && (isRecording || showProgress) && (
<View <View
style={{ style={{
@@ -374,18 +382,15 @@ const RecordPlayback = ({ route }) => {
justifyContent: "center", justifyContent: "center",
}} }}
> >
{/* Dimmed circular backdrop */}
<View <View
style={{ style={{
width: 100, width: 100,
height: 100, height: 100,
borderRadius: 105, borderRadius: 105,
// backgroundColor: Palette.ultraLightBlack,
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
}} }}
> >
{/* Progress ring */}
<ProgressRing <ProgressRing
size={100} size={100}
strokeWidth={8} strokeWidth={8}
@@ -395,7 +400,6 @@ const RecordPlayback = ({ route }) => {
: 0 : 0
} }
/> />
{/* Center white button-like circle */}
<View <View
style={{ style={{
position: "absolute", position: "absolute",
@@ -414,7 +418,7 @@ const RecordPlayback = ({ route }) => {
); );
}; };
// Simple SVG circular progress ring // Progress ring SVG
const ProgressRing = ({ size = 50, strokeWidth = 12, progress = 0 }) => { const ProgressRing = ({ size = 50, strokeWidth = 12, progress = 0 }) => {
const r = size / 2 - strokeWidth / 2; const r = size / 2 - strokeWidth / 2;
const c = 2 * Math.PI * r; const c = 2 * Math.PI * r;