When using the RNSound library, I ran into a problem - I can't pause the sound.
initialize :
Sound.setCategory("Playback");
let whoosh = new Sound("complite.mp3", Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log("failed to load the sound", error);
return;
}
})
and use like this:
<Button
onPress={() => {
if (!start) {
whoosh.play();
const myTimer = setInterval(() => {
setCounter((counter) => counter - 1);
}, 1000);
setTimer(myTimer);
setStart((start) => !start);
} else {
whoosh.pause();
clearInterval(timer);
setCounter(null);
setStart((start) => !start);
}
}}
the first time the button is pressed, the sound is played. On the second press, nothing happens and music is playing. On the third press, the same melody runs in parallel for the second time. As far as I understand, each time I click on the button, I refer to a new instance of Sound. Help with a solution please.
p.s. - i need solution with functional component, not a class. Thanks.
Declare the Sound instance outside of your component scope. You don't need to create a new instance of Sound everytime. Refer my sample.
Sound.setCategory('Playback');
var whoosh = new Sound('beep.mp3', Sound.MAIN_BUNDLE, error => {
if (error) {
console.log('failed to load the sound', error);
return;
}
// loaded successfully
console.log(
'duration in seconds: ' +
whoosh.getDuration() +
'number of channels: ' +
whoosh.getNumberOfChannels(),
);
});
const App: () => Node = () => {
const [start, setStart] = useState(false);
const [counter, setCounter] = useState(0);
const [timer, setTimer] = useState(null);
return (
<Button
onPress={() => {
if (!start) {
whoosh.play();
const myTimer = setInterval(() => {
setCounter(counter => counter - 1);
}, 1000);
setTimer(myTimer);
setStart(start => !start);
} else {
whoosh.pause();
clearInterval(timer);
setCounter(null);
setStart(start => !start);
}
}}
title="Click me"
/>
);
};
Let me know how it goes.