I’m encountering an error related to audio playback in my React Native/Expo application. The application includes a feature where background music plays while a timer counts down (think of a pomodoro app for example). There is a start/reset button used to start or reset the timer. However, I’m encountering an “Possible Unhandled Promise Rejection (id: 0) Error” when attempting to reset the sound playback. The sound stops playing when the reset button is clicked but an expo error warning pops up on my simulator/device. What might be the issue for this problem?
The code is attached below –
import React, { useState, useEffect } from "react";
import { Audio } from "expo-av";
const TimerComponent = () => {
const [time, setTime] = useState(60);
const [isRunning, setIsRunning] = useState(false);
const [sound, setSound] = useState<Audio.Sound | null>(null);
useEffect(() => {
let interval: any;
if (isRunning) {
try {
interval = setInterval(() => {
setTime((prevTime) => {
if (prevTime === 0) {
clearInterval(interval);
setIsRunning(false);
resetTimer();
stopSound();
return 60;
} else {
return prevTime - 1;
}
});
}, 1000);
} catch (error) {
console.log("Error: ", error);
}
} else {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [isRunning]);
const toggleTimer = () => {
if (isRunning) {
setIsRunning(false);
stopSound();
resetTimer();
} else {
setIsRunning(true);
playSound();
}
};
const playSound = async () => {
try {
const { sound } = await Audio.Sound.createAsync(
require("../../assets/ambient_music.mp3"),
{ shouldPlay: true }
);
setSound(sound);
} catch (error) {
console.error(error);
}
};
const stopSound = async () => {
if (sound) {
await sound.stopAsync();
await sound.unloadAsync();
setSound(null);
}
};
const resetTimer = () => {
setTime(60);
};
useEffect(() => {
if (!isRunning) {
try {
stopSound();
} catch (error) {
console.log("Error: ", error);
}
}
}, [isRunning]);
return null;
};
export default TimerComponent;
I have tried to fixed this issue by trying out try-catch blocks but it doesn’t help much. I don’t know why this is happening and I would appreciate any help or feeedbacks.