[英]Access const inside async function in react-native / expo
I am trying to use the expo-av lib 我正在尝试使用expo-av lib
I use the following async function to play a sound file from an URL: 我使用以下异步函数从URL播放声音文件:
PlaySound = async (soundURL) => {
try {
const playbackObject = await Audio.Sound.createAsync(
{ uri: soundURL },
{ shouldPlay: this.state.shouldPlay }
);
} catch (error) {
console.log('ERROR:'+error);
// Error retrieving data
}
return playbackObject;
};
stopSound = async (soundURL) => {
try {
this.setState({shouldPlay:false});
const playbackObject = await PlaySound(soundURL);
} catch (error) {
console.log('ERROR:'+error);
// Error retrieving data
}
playbackObject.stopAsync(); // this is causing the error
};
I get this error: 我收到此错误:
ERROR:ReferenceError: Can't find variable: playbackObject 错误:ReferenceError:找不到变量:playingObject
[Unhandled promise rejection: ReferenceError: Can't find variable: playbackObject] [未处理的承诺拒绝:ReferenceError:找不到变量:playingObject]
The PlaySound
functions works as I want. PlaySound
函数可以根据需要工作。 Now I want to be able to pause/stop using the stopSound
function. 现在,我希望能够使用stopSound
函数暂停/停止。 The documentation says to use soundObject.stopAsync()
which in my case would be playbackObject
. 文档说,使用soundObject.stopAsync()
这在我的情况下,将playbackObject
。 But I can't figure out how to access this const outside of the function? 但是我不知道如何在函数外部访问此const?
Can anyone point me in the right direction? 谁能指出我正确的方向?
You cannot reference a const that was defined inside of a try/catch outside of the try catch. 您不能引用在try catch之外的try / catch内部定义的const。 You can fix this by doing either of the following: 您可以通过以下任一方法解决此问题:
let playbackObject;
try {
playbackObject = await Audio.Sound.createAsync(
{ uri: soundURL },
{ shouldPlay: this.state.shouldPlay }
);
} catch (error) {
console.log('ERROR:'+error);
// Error retrieving data
}
return playbackObject;
or 要么
try {
return Audio.Sound.createAsync(
{ uri: soundURL },
{ shouldPlay: this.state.shouldPlay }
);
} catch (error) {
console.log('ERROR:'+error);
// Error retrieving data
}
In order to fix the stop function, you should maintain a reference to the playbackObject that is returned by the start function and use that in the stop function, since the way you currently have it would create a new audio stream that you would then stop (leaving the original in tact). 为了修复stop函数,您应该维护对start函数返回的playingObject的引用,并在stop函数中使用该引用,因为您当前拥有的方式会创建一个新的音频流,然后停止该音频流(保持原样不变)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.