Skip to content

Commit

Permalink
Fix seeking in native audio player
Browse files Browse the repository at this point in the history
  • Loading branch information
thornbill committed Mar 28, 2022
1 parent 0253a01 commit 9826f8b
Showing 1 changed file with 31 additions and 23 deletions.
54 changes: 31 additions & 23 deletions components/AudioPlayer.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,36 +29,44 @@ const AudioPlayer = observer(() => {
});

return () => {
player?.stopAsync();
player?.unloadAsync();
};
}, []);

// Update the player when media type or uri changes
useEffect(() => {
const createPlayer = async ({ uri, positionMillis }) => {
const { sound } = await Audio.Sound.createAsync({
uri
}, {
positionMillis,
shouldPlay: true
}, ({
isPlaying,
positionMillis: positionMs,
didJustFinish
}) => {
if (
didJustFinish === undefined ||
isPlaying === undefined ||
positionMs === undefined ||
rootStore.mediaStore.isFinished
) {
return;
}
rootStore.mediaStore.isFinished = didJustFinish;
rootStore.mediaStore.isPlaying = isPlaying;
rootStore.mediaStore.positionTicks = msToTicks(positionMs);
});
setPlayer(sound);
const { isLoaded } = await player?.getStatusAsync() || { isLoaded: false };
if (isLoaded) {
// If the player is already loaded, seek to the correct position
player.setPositionAsync(positionMillis);
} else {
// Create the player if not already loaded
const { sound } = await Audio.Sound.createAsync({
uri
}, {
positionMillis,
shouldPlay: true
}, ({
isPlaying,
positionMillis: positionMs,
didJustFinish
}) => {
if (
didJustFinish === undefined ||
isPlaying === undefined ||
positionMs === undefined ||
rootStore.mediaStore.isFinished
) {
return;
}
rootStore.mediaStore.isFinished = didJustFinish;
rootStore.mediaStore.isPlaying = isPlaying;
rootStore.mediaStore.positionTicks = msToTicks(positionMs);
});
setPlayer(sound);
}
};

if (rootStore.mediaStore.type === MediaTypes.Audio) {
Expand Down

0 comments on commit 9826f8b

Please sign in to comment.