API/Hooks
usePlayer
The usePlayer
hook provides reactive state updates for playback progress, status, and current metadata from the Expo Sonic iOS Player. This hook abstracts away event handling for status and playback updates.
🛠️ Import
import { usePlayer } from "expo-sonic-ios-player";
✅ Usage
const { status, isPlaying, duration, currentTime, progress, remainingTime } =
usePlayer();
🔁 Event Subscriptions
Internally, this hook subscribes to:
onStatusChange
– to update the player status (loading
,ready
,seeked
,error
)onPlaybackInfo
– to update current playback position, duration, and playback state
🧠 Returned Values
Property | Type | Description |
---|---|---|
status | StatusType | Current playback status: "loading" , "ready" , "seeked" , "error" , or "unknown" |
isPlaying | boolean | Whether audio is currently playing |
duration | number | Total duration of the audio (in seconds) |
currentTime | number | Current playback position (in seconds) |
progress | number | Fractional progress between 0 and 1 (currentTime / duration ) |
remainingTime | number | Time remaining in seconds (duration - currentTime ) |
🧩 Hook Code
import { useEffect, useState } from "react";
import RNExpoSonicPlayerModule from "../RNSonicModule";
type StatusType = "loading" | "ready" | "error" | "seeked" | "unknown";
export function usePlayer() {
const [status, setStatus] = useState<StatusType>("unknown");
const [isPlaying, setIsPlaying] = useState(false);
const [duration, setDuration] = useState(0);
const [currentTime, setCurrentTime] = useState(0);
useEffect(() => {
const statusSub = RNExpoSonicPlayerModule.addListener(
"onStatusChange",
(event) => {
setStatus(event.status);
}
);
const playbackSub = RNExpoSonicPlayerModule.addListener(
"onPlaybackInfo",
(event) => {
setCurrentTime(event.currentTime ?? 0);
setDuration(event.duration ?? 0);
setIsPlaying(event.isPlaying ?? false);
}
);
return () => {
statusSub.remove();
playbackSub.remove();
};
}, []);
const progress = duration > 0 ? currentTime / duration : 0;
const remainingTime = Math.max(duration - currentTime, 0);
return {
status,
isPlaying,
duration,
currentTime,
progress,
remainingTime,
};
}