diff --git a/src/screens/Playback/RecordPlayback.js b/src/screens/Playback/RecordPlayback.js
index 9396382..7f1699b 100644
--- a/src/screens/Playback/RecordPlayback.js
+++ b/src/screens/Playback/RecordPlayback.js
@@ -1,20 +1,29 @@
+import { useFocusEffect } from "@react-navigation/native";
+import { useAudioPlayer } from "expo-audio";
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 { useSafeAreaInsets } from "react-native-safe-area-context";
+import Svg, { Circle } from "react-native-svg";
import GradientButton from "../../components/GradientButton";
import MusicLandHeader from "../../components/MusicLandHeader";
+import { increment, projectsRef } from "../../config/firebase";
import { Routes } from "../../navigation";
import { goBack, navigate } from "../../navigation/NavigationService";
import { gutters, Palette } from "../../styles";
import { FONT_FAMILY } from "../../styles/Fonts";
import CreateLyricsHeader from "../Writing/components/CreateLyricsHeader";
-// ADD: Firestore helpers to increment views
-import { useFocusEffect } from "@react-navigation/native";
-import { useAudioPlayer } from "expo-audio";
-import { useCallback, useEffect, useRef, useState } from "react";
-import Svg, { Circle } from "react-native-svg";
-import { increment, projectsRef } from "../../config/firebase";
+
+/**
+ * RecordPlayback — refactor robuste du compteur
+ *
+ * Correction de l'auto-start : on garde un flag countdownActiveRef pour
+ * 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 { top } = useSafeAreaInsets();
const { project } = route.params || {};
@@ -25,13 +34,15 @@ const RecordPlayback = ({ route }) => {
// Refs
const cameraRef = useRef(null);
const countdownTimerRef = useRef(null);
+ const listenTimerRef = useRef(null);
+ const checkSongEndRef = useRef(null);
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 incrementDoneRef = useRef(false);
- const timerRef = useRef(null);
- const timeBeforeIncrement = 20000; // 20 seconds
// UI / state
const [isPreparing, setIsPreparing] = useState(false);
@@ -40,70 +51,74 @@ const RecordPlayback = ({ route }) => {
const [showProgress, setShowProgress] = useState(false);
const [progressInfo, setProgressInfo] = useState({ pos: 0, dur: 0 });
- // Derive song URL robustly
+ // Musique
const songUrl = project?.songUrl || null;
const player = useAudioPlayer(songUrl ? { uri: songUrl } : undefined);
- // useEffect(() => {
- // setVideo(null);
- // }, []);
+
useEffect(() => {
listenedMsRef.current = 0;
incrementDoneRef.current = false;
}, [songUrl]);
- // Poll player state to update progress ring
+ // Poll player -> progress ring
useEffect(() => {
if (!player) return;
- const id = global.setInterval(() => {
+ const id = setInterval(() => {
try {
const dur = (player?.duration || 0) * 1000;
const pos = (player?.currentTime || 0) * 1000;
setProgressInfo({ pos, dur });
} catch (_) {}
}, 250);
- return () => global.clearInterval(id);
+ return () => clearInterval(id);
}, [player]);
+ // Permissions au mount + cleanup
useEffect(() => {
- // Request permissions on mount if not granted
(async () => {
try {
if (!cameraPermission?.granted) await requestCameraPermission();
} catch (_) {}
})();
return () => {
- // Cleanup timers on unmount
try {
- if (countdownTimerRef.current) {
- global.clearInterval(countdownTimerRef.current);
- countdownTimerRef.current = null;
- }
- if (timerRef.current) {
- global.clearInterval(timerRef.current);
- timerRef.current = null;
- }
+ if (countdownTimerRef.current) clearInterval(countdownTimerRef.current);
+ if (listenTimerRef.current) clearInterval(listenTimerRef.current);
+ if (checkSongEndRef.current) clearInterval(checkSongEndRef.current);
+ countdownTimerRef.current = null;
+ listenTimerRef.current = null;
+ checkSongEndRef.current = null;
} 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 () => {
try {
if (countdownTimerRef.current) {
- global.clearInterval(countdownTimerRef.current);
+ clearInterval(countdownTimerRef.current);
countdownTimerRef.current = null;
}
- if (timerRef.current) {
- global.clearInterval(timerRef.current);
- timerRef.current = null;
+ if (listenTimerRef.current) {
+ clearInterval(listenTimerRef.current);
+ listenTimerRef.current = null;
}
+ if (checkSongEndRef.current) {
+ clearInterval(checkSongEndRef.current);
+ checkSongEndRef.current = null;
+ }
+
+ startedRef.current = false;
stopRequestedRef.current = false;
+ countdownActiveRef.current = false;
listenedMsRef.current = 0;
incrementDoneRef.current = false;
+
setIsPreparing(false);
setIsRecording(false);
setShowProgress(false);
setCountdown(0);
+
if (player) {
try {
if (player.playing) await player.pause?.();
@@ -113,7 +128,6 @@ const RecordPlayback = ({ route }) => {
} catch (_) {}
}, [player]);
- // Reset when screen gains focus (coming from "Recommencer", etc.)
useFocusEffect(
useCallback(() => {
void resetSession();
@@ -121,64 +135,59 @@ const RecordPlayback = ({ route }) => {
}, [resetSession])
);
+ // Lancer le compte à rebours (le tick décrémente uniquement)
const startCountdownThenRecord = async () => {
- console.log("start countdown");
if (!songUrl) return;
- console.log("songUrl exists");
- // Ensure clean state and audio at t=0
await resetSession();
setIsPreparing(true);
- setCountdown(5);
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) {
- global.clearInterval(countdownTimerRef.current);
+ clearInterval(countdownTimerRef.current);
countdownTimerRef.current = null;
}
- countdownTimerRef.current = global.setInterval(() => {
- setCountdown((c) => {
- const next = (c || 0) - 1;
- if (next <= 0) {
- console.log("clear timer");
- // clear timer
- global.clearInterval(countdownTimerRef.current);
- countdownTimerRef.current = null;
- // Ensure countdown overlay disappears and progress shows immediately
- setIsPreparing(false);
- 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();
- }
- return Math.max(0, next);
- });
+ countdownTimerRef.current = setInterval(() => {
+ setCountdown((c) => Math.max(0, c - 1));
}, 1000);
+ countdownActiveRef.current = true;
};
+ // 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;
+ }
+ countdownActiveRef.current = false;
+ // Bascule après rendu de la frame courante
+ requestAnimationFrame(() => {
+ setIsPreparing(false);
+ setShowProgress(true);
+ void startRecordingWithMusic();
+ });
+ }
+ }, [countdown, isPreparing]);
+
const startRecordingWithMusic = async () => {
try {
stopRequestedRef.current = false;
-
- // Reset listen counters for this track/session
listenedMsRef.current = 0;
incrementDoneRef.current = false;
- // Start recording
setIsRecording(true);
- setCountdown(0);
- setIsPreparing(false);
setShowProgress(true);
const recordPromise = cameraRef.current?.recordAsync?.({
mute: true,
- maxDuration: 600, // safety cap (10 min)
+ maxDuration: 600,
});
- // Start playing with useAudioPlayer (like MusicDetails)
if (player && songUrl) {
try {
await player.seekTo?.(0);
@@ -186,15 +195,15 @@ const RecordPlayback = ({ route }) => {
await player.play?.();
}
- // Start timer to track listening time and increment views (like MusicDetails)
- if (!timerRef.current && project?.id) {
- timerRef.current = global.setInterval(async () => {
+ // Incrément des vues
+ if (!listenTimerRef.current && project?.id) {
+ listenTimerRef.current = setInterval(async () => {
try {
if (player?.playing) {
listenedMsRef.current += 500;
if (
!incrementDoneRef.current &&
- listenedMsRef.current >= timeBeforeIncrement
+ listenedMsRef.current >= TIME_BEFORE_INCREMENT_MS
) {
incrementDoneRef.current = true;
try {
@@ -208,61 +217,62 @@ const RecordPlayback = ({ route }) => {
}, 500);
}
- // Monitor when song ends to stop recording
- const checkSongEnd = global.setInterval(async () => {
- try {
- if (player && !player.playing && !stopRequestedRef.current) {
+ // Fin du morceau -> stop recording
+ if (!checkSongEndRef.current) {
+ checkSongEndRef.current = setInterval(() => {
+ try {
+ if (!player) return;
const duration = (player?.duration || 0) * 1000;
const currentTime = (player?.currentTime || 0) * 1000;
-
- // If we're near the end or stopped, stop recording
- if (duration > 0 && currentTime >= duration - 1000) {
+ if (
+ (!player.playing && !stopRequestedRef.current) ||
+ (duration > 0 && currentTime >= duration - 600)
+ ) {
stopRequestedRef.current = true;
- global.clearInterval(checkSongEnd);
+ if (checkSongEndRef.current) {
+ clearInterval(checkSongEndRef.current);
+ checkSongEndRef.current = null;
+ }
try {
cameraRef.current?.stopRecording?.();
} catch (_) {}
}
- }
- } catch (_) {}
- }, 1000);
+ } catch (_) {}
+ }, 500);
+ }
- // Wait for recording to stop
const video = await recordPromise;
- global.clearInterval(checkSongEnd);
- // Stop audio
+ if (checkSongEndRef.current) {
+ clearInterval(checkSongEndRef.current);
+ checkSongEndRef.current = null;
+ }
try {
- if (player?.playing) {
- await player.pause?.();
- }
+ if (player?.playing) await player.pause?.();
} catch (_) {}
-
- // Clear listen timer after recording ends
- if (timerRef.current) {
- global.clearInterval(timerRef.current);
- timerRef.current = null;
+ if (listenTimerRef.current) {
+ clearInterval(listenTimerRef.current);
+ listenTimerRef.current = null;
}
setIsRecording(false);
- setIsPreparing(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 });
- } else {
- navigate(Routes.RecordedPlayback, { project });
- }
+ else navigate(Routes.RecordedPlayback, { project });
} catch (e) {
- // Fallback on error
- console.log("error : ", e);
+ console.log("RecordPlayback error:", e);
setIsRecording(false);
setIsPreparing(false);
setShowProgress(false);
- if (timerRef.current) {
- global.clearInterval(timerRef.current);
- timerRef.current = null;
+ if (listenTimerRef.current) {
+ clearInterval(listenTimerRef.current);
+ listenTimerRef.current = null;
+ }
+ if (checkSongEndRef.current) {
+ clearInterval(checkSongEndRef.current);
+ checkSongEndRef.current = null;
}
}
};
@@ -286,6 +296,7 @@ const RecordPlayback = ({ route }) => {
}}
>
+
{
- {/* Centered countdown overlay */}
- {isPreparing && countdown > 0 && !showProgress && (
+ {/* Overlay de compte à rebours : on affiche 5→1 pour éviter l'effet visuel à 1 */}
+ {isPreparing && countdown >= 1 && !showProgress && (
{
{permissionsGranted && !isPreparing && !isRecording && (
)}
- {/* Circular progress when countdown finished / recording */}
+ {/* Progress circulaire */}
{permissionsGranted && (isRecording || showProgress) && (
{
justifyContent: "center",
}}
>
- {/* Dimmed circular backdrop */}
- {/* Progress ring */}
{
: 0
}
/>
- {/* Center white button-like circle */}
{
);
};
-// Simple SVG circular progress ring
+// Progress ring SVG
const ProgressRing = ({ size = 50, strokeWidth = 12, progress = 0 }) => {
const r = size / 2 - strokeWidth / 2;
const c = 2 * Math.PI * r;