playback
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
import { Audio } from "expo-audio";
|
||||
import { CameraView, useCameraPermissions } from "expo-camera";
|
||||
import React from "react";
|
||||
import { Text, View } from "react-native";
|
||||
@@ -10,7 +9,12 @@ 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";
|
||||
const RecordPlayback = ({ route }) => {
|
||||
const { top } = useSafeAreaInsets();
|
||||
const { project } = route.params || {};
|
||||
@@ -19,20 +23,48 @@ const RecordPlayback = ({ route }) => {
|
||||
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
|
||||
|
||||
// Refs
|
||||
const cameraRef = React.useRef(null);
|
||||
const soundRef = React.useRef(null);
|
||||
const countdownTimerRef = React.useRef(null);
|
||||
const stopRequestedRef = React.useRef(false);
|
||||
const cameraRef = useRef(null);
|
||||
const countdownTimerRef = useRef(null);
|
||||
const stopRequestedRef = useRef(false);
|
||||
|
||||
// Listen counter refs (inspired by MusicDetails)
|
||||
const listenedMsRef = useRef(0);
|
||||
const incrementDoneRef = useRef(false);
|
||||
const timerRef = useRef(null);
|
||||
const timeBeforeIncrement = 20000; // 20 seconds
|
||||
|
||||
// UI / state
|
||||
const [isPreparing, setIsPreparing] = React.useState(false);
|
||||
const [countdown, setCountdown] = React.useState(0);
|
||||
const [isRecording, setIsRecording] = React.useState(false);
|
||||
const [isPreparing, setIsPreparing] = useState(false);
|
||||
const [countdown, setCountdown] = useState(0);
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
const [showProgress, setShowProgress] = useState(false);
|
||||
const [progressInfo, setProgressInfo] = useState({ pos: 0, dur: 0 });
|
||||
|
||||
// Derive song URL robustly
|
||||
const songUrl = project?.songUrl || null;
|
||||
const player = useAudioPlayer(songUrl ? { uri: songUrl } : undefined);
|
||||
// useEffect(() => {
|
||||
// setVideo(null);
|
||||
// }, []);
|
||||
useEffect(() => {
|
||||
listenedMsRef.current = 0;
|
||||
incrementDoneRef.current = false;
|
||||
}, [songUrl]);
|
||||
|
||||
React.useEffect(() => {
|
||||
// Poll player state to update progress ring
|
||||
useEffect(() => {
|
||||
if (!player) return;
|
||||
const id = global.setInterval(() => {
|
||||
try {
|
||||
const dur = (player?.duration || 0) * 1000;
|
||||
const pos = (player?.currentTime || 0) * 1000;
|
||||
setProgressInfo({ pos, dur });
|
||||
} catch (_) {}
|
||||
}, 250);
|
||||
return () => global.clearInterval(id);
|
||||
}, [player]);
|
||||
|
||||
useEffect(() => {
|
||||
// Request permissions on mount if not granted
|
||||
(async () => {
|
||||
try {
|
||||
@@ -40,40 +72,88 @@ const RecordPlayback = ({ route }) => {
|
||||
} catch (_) {}
|
||||
})();
|
||||
return () => {
|
||||
// Cleanup timers and audio on unmount
|
||||
// Cleanup timers on unmount
|
||||
try {
|
||||
if (countdownTimerRef.current) {
|
||||
global.clearInterval(countdownTimerRef.current);
|
||||
countdownTimerRef.current = null;
|
||||
}
|
||||
(async () => {
|
||||
try {
|
||||
if (soundRef.current) {
|
||||
soundRef.current.setOnPlaybackStatusUpdate(null);
|
||||
await soundRef.current.unloadAsync();
|
||||
soundRef.current = null;
|
||||
}
|
||||
} catch (_) {}
|
||||
})();
|
||||
if (timerRef.current) {
|
||||
global.clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
} catch (_) {}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Fully reset audio and recording state (used on focus and before new session)
|
||||
const resetSession = useCallback(async () => {
|
||||
try {
|
||||
if (countdownTimerRef.current) {
|
||||
global.clearInterval(countdownTimerRef.current);
|
||||
countdownTimerRef.current = null;
|
||||
}
|
||||
if (timerRef.current) {
|
||||
global.clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
stopRequestedRef.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?.();
|
||||
await player.seekTo?.(0);
|
||||
} catch (_) {}
|
||||
}
|
||||
} catch (_) {}
|
||||
}, [player]);
|
||||
|
||||
// Reset when screen gains focus (coming from "Recommencer", etc.)
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
void resetSession();
|
||||
return () => {};
|
||||
}, [resetSession])
|
||||
);
|
||||
|
||||
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);
|
||||
// Start music + recording immediately when countdown starts
|
||||
void startRecordingWithMusic();
|
||||
// 5 -> 0 countdown display only
|
||||
setShowProgress(false);
|
||||
|
||||
// Start countdown display; start recording+music WHEN countdown reaches 0
|
||||
if (countdownTimerRef.current) {
|
||||
global.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);
|
||||
});
|
||||
@@ -83,70 +163,90 @@ const RecordPlayback = ({ route }) => {
|
||||
const startRecordingWithMusic = async () => {
|
||||
try {
|
||||
stopRequestedRef.current = false;
|
||||
console.log("stop requested ref is : ", soundRef.current);
|
||||
// Prepare audio
|
||||
if (soundRef.current) {
|
||||
console.log("if sound ref current");
|
||||
try {
|
||||
soundRef.current.setOnPlaybackStatusUpdate(null);
|
||||
await soundRef.current.unloadAsync();
|
||||
console.log("unload sound ref");
|
||||
} catch (_) {}
|
||||
soundRef.current = null;
|
||||
}
|
||||
|
||||
// Ensure audio mode allows playback alongside camera recording
|
||||
try {
|
||||
await Audio.setAudioModeAsync({
|
||||
playsInSilentMode: true,
|
||||
interruptionMode: "mixWithOthers",
|
||||
allowsRecording: true,
|
||||
shouldPlayInBackground: false,
|
||||
});
|
||||
} catch (_) {}
|
||||
|
||||
const { sound } = await Audio.Sound.createAsync(
|
||||
{ uri: songUrl },
|
||||
{ shouldPlay: false }
|
||||
);
|
||||
|
||||
sound.setOnPlaybackStatusUpdate((status) => {
|
||||
if (!status || !status.isLoaded) return;
|
||||
if (status.didJustFinish && !stopRequestedRef.current) {
|
||||
stopRequestedRef.current = true;
|
||||
try {
|
||||
cameraRef.current?.stopRecording?.();
|
||||
} catch (_) {}
|
||||
}
|
||||
});
|
||||
soundRef.current = sound;
|
||||
// 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)
|
||||
});
|
||||
|
||||
// Start playing
|
||||
await sound.playAsync();
|
||||
// Start playing with useAudioPlayer (like MusicDetails)
|
||||
if (player && songUrl) {
|
||||
try {
|
||||
await player.seekTo?.(0);
|
||||
} catch (_) {}
|
||||
await player.play?.();
|
||||
}
|
||||
|
||||
// Wait for recording to stop (either by song end or manual stop)
|
||||
// Start timer to track listening time and increment views (like MusicDetails)
|
||||
if (!timerRef.current && project?.id) {
|
||||
timerRef.current = global.setInterval(async () => {
|
||||
try {
|
||||
if (player?.playing) {
|
||||
listenedMsRef.current += 500;
|
||||
if (
|
||||
!incrementDoneRef.current &&
|
||||
listenedMsRef.current >= timeBeforeIncrement
|
||||
) {
|
||||
incrementDoneRef.current = true;
|
||||
try {
|
||||
await projectsRef
|
||||
.doc(project.id)
|
||||
.set({ views: increment(1) }, { merge: true });
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
}, 500);
|
||||
}
|
||||
|
||||
// Monitor when song ends to stop recording
|
||||
const checkSongEnd = global.setInterval(async () => {
|
||||
try {
|
||||
if (player && !player.playing && !stopRequestedRef.current) {
|
||||
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) {
|
||||
stopRequestedRef.current = true;
|
||||
global.clearInterval(checkSongEnd);
|
||||
try {
|
||||
cameraRef.current?.stopRecording?.();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
}, 1000);
|
||||
|
||||
// Wait for recording to stop
|
||||
const video = await recordPromise;
|
||||
global.clearInterval(checkSongEnd);
|
||||
|
||||
// Ensure audio stops and cleanup
|
||||
// Stop audio
|
||||
try {
|
||||
const s = soundRef.current;
|
||||
if (s) {
|
||||
s.setOnPlaybackStatusUpdate(null);
|
||||
await s.stopAsync().catch(() => {});
|
||||
await s.unloadAsync().catch(() => {});
|
||||
if (player?.playing) {
|
||||
await player.pause?.();
|
||||
}
|
||||
} catch (_) {}
|
||||
soundRef.current = null;
|
||||
|
||||
// Clear listen timer after recording ends
|
||||
if (timerRef.current) {
|
||||
global.clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
|
||||
setIsRecording(false);
|
||||
setIsPreparing(false);
|
||||
setShowProgress(false);
|
||||
|
||||
// Navigate to next screen with video uri if available
|
||||
if (video?.uri) {
|
||||
@@ -156,13 +256,14 @@ const RecordPlayback = ({ route }) => {
|
||||
}
|
||||
} catch (e) {
|
||||
// Fallback on error
|
||||
console.log("error : ", e);
|
||||
setIsRecording(false);
|
||||
setIsPreparing(false);
|
||||
try {
|
||||
soundRef.current?.setOnPlaybackStatusUpdate?.(null);
|
||||
await soundRef.current?.unloadAsync?.();
|
||||
} catch (_) {}
|
||||
soundRef.current = null;
|
||||
setShowProgress(false);
|
||||
if (timerRef.current) {
|
||||
global.clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -200,7 +301,7 @@ const RecordPlayback = ({ route }) => {
|
||||
</CreateLyricsHeader>
|
||||
|
||||
{/* Centered countdown overlay */}
|
||||
{(isPreparing || isRecording) && countdown > 0 && (
|
||||
{isPreparing && countdown > 0 && !showProgress && (
|
||||
<View
|
||||
style={{
|
||||
position: "absolute",
|
||||
@@ -260,10 +361,88 @@ const RecordPlayback = ({ route }) => {
|
||||
onPress={startCountdownThenRecord}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Circular progress when countdown finished / recording */}
|
||||
{permissionsGranted && (isRecording || showProgress) && (
|
||||
<View
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: gutters,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{/* Dimmed circular backdrop */}
|
||||
<View
|
||||
style={{
|
||||
width: 100,
|
||||
height: 100,
|
||||
borderRadius: 105,
|
||||
// backgroundColor: Palette.ultraLightBlack,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{/* Progress ring */}
|
||||
<ProgressRing
|
||||
size={100}
|
||||
strokeWidth={8}
|
||||
progress={
|
||||
progressInfo.dur
|
||||
? Math.min(1, (progressInfo.pos || 0) / progressInfo.dur)
|
||||
: 0
|
||||
}
|
||||
/>
|
||||
{/* Center white button-like circle */}
|
||||
<View
|
||||
style={{
|
||||
position: "absolute",
|
||||
width: 50,
|
||||
height: 50,
|
||||
borderRadius: 55,
|
||||
backgroundColor: Palette.white,
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</CameraView>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
// Simple SVG circular progress ring
|
||||
const ProgressRing = ({ size = 50, strokeWidth = 12, progress = 0 }) => {
|
||||
const r = size / 2 - strokeWidth / 2;
|
||||
const c = 2 * Math.PI * r;
|
||||
const clamped = Math.max(0, Math.min(1, progress || 0));
|
||||
const offset = c * (1 - clamped);
|
||||
return (
|
||||
<Svg
|
||||
width={size}
|
||||
height={size}
|
||||
style={{
|
||||
transform: [{ rotate: "-90deg" }],
|
||||
backgroundColor: "#ffffff3d",
|
||||
borderRadius: 55,
|
||||
}}
|
||||
>
|
||||
<Circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={r}
|
||||
stroke={Palette.white}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={`${c} ${c}`}
|
||||
strokeDashoffset={offset}
|
||||
fill="transparent"
|
||||
/>
|
||||
</Svg>
|
||||
);
|
||||
};
|
||||
|
||||
export default RecordPlayback;
|
||||
|
||||
Reference in New Issue
Block a user