什么是正确的方法来使用反应原生声音?



在使用RNSound库时,我遇到了一个问题-我无法暂停声音。

初始化:

Sound.setCategory("Playback");
let whoosh = new Sound("complite.mp3", Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log("failed to load the sound", error);
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);
}
}}

第一次按下按钮,播放声音。第二次按压时,什么也没发生,音乐正在播放。在第三次按压时,同样的旋律第二次平行播放。据我所知,每次点击按钮时,我都会引用一个新的Sound实例。请帮忙解决。

注。-我需要功能组件的解决方案,而不是类。谢谢。

在组件作用域之外声明Sound实例。你不需要每次都创建一个新的Sound实例。参考我的示例。

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"
/>
);
};

让我知道进展如何

最新更新