I have a problem which I cannot get my head around. I want to play a sound, display an image and display some text from the same array positions in three different arrays( ord
, images
& ljud
) where the sound, image and text is stored in the corresponding positions.
Everything works fine(image displays, text displays and sound plays). However, the sound and the image does not match when pressing the TouchableOpacity
. I tried console logging the imgIndex
value and it seems like the text/image display function is one step behind the sound playing even though the object are loaded from the same variable imgIndex
. It seems to be a problem with the Async function loading the Audio. The warning I get during the first press on the TouchableOpacity
is the following:
“Cannot load an AV asset from a null playback source”
Seems like the first imgIndex
value is loaded as a null value into the handlePlaySound function even if it should be 1 or 2? Can I rewrite the async function or can I play sounds without using an async function?
I would be really glad if anyone could point me in the right direction here.
Thank you!
Richard
const ljud = [require('./assets/apa.mp3'),require('./assets/bil.mp3')];
export default class A extends React.Component {
constructor () {
super();
this.state = {
showImageA: false,
imgIndex: []
};
}
ord = ['apa','bil'];
images = [require('./assets/apa.png'),require('./assets/bil.png')];
displayRandomImage = () => {
this.setState({
imgIndex: Math.floor(Math.random() * 2)
});
this.setState({showImageA: true});
setTimeout(() => {
this.setState({showImageA: false});
}, 1000);
}
handlePlaySound= async note => {
const soundObject = new Audio.Sound()
try {
let source = ljud[note]
await soundObject.loadAsync(source)
await soundObject
.playAsync()
.then(async playbackStatus => {
setTimeout(() => {
soundObject.unloadAsync()
}, playbackStatus.playableDurationMillis)
})
.catch(error => {
console.log(error)
})
} catch (error) {
console.log(error)
}
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<LinearGradient
colors={['rgba(25,172,255,0.8)', 'cyan']}
style={{
position: 'absolute',
left: 0,
right: 0,
top: 0,
height: 800,
}}
/>
<Text style={styles.buttonTextTop}>MAX ABC</Text>
<Text style={styles.buttonTextVersion}>ver 0.2</Text>
{this.state.showImageA &&
<View>
<Image
style={styles.img}
source={this.images[this.state.imgIndex]} />
<Text
style={styles.buttonText}>{this.ord[this.state.imgIndex]}
</Text>
</View>}
<TouchableOpacity
style={[styles.button]}
onPress={() => {this.displayRandomImage(); this.handlePlaySound(this.state.imgIndex);}}>
<Text style={styles.buttonText}>A</Text>
</TouchableOpacity>
</View>
);
}
}