I am using Audio from expo-av in react-native-expo.
I can run the audio using loadAsync method on Audio.sound contructor.
Although when I try to stop the voice it doesn't stop the voice.
Following is the minimalistic code snippet. Is this the correct way to stop the sound. I am not able to find the solution for this.
import React, {useState, useEffect} from 'react';
import { Button } from 'react-native';
import { Audio } from 'expo-av';
export default function App() {
const [audioStatus, setAudioStatus] = useState(false)
const sound = new Audio.Sound();
useEffect(()=>{
(async () => {
console.log('status', audioStatus)
if (audioStatus) {
await sound.loadAsync('.mp3')
try {
await sound.playAsync()
} catch (e) {
console.log(e)
}
}else {
await sound.stopAsync()
await sound.unloadAsync()
}
})()
},[audioStatus])
return (
<Button color={audioStatus ? 'red' : 'green'} title={'play'} onPress={()=>setAudioStatus(!audioStatus)} />
);
}
Thanks in Advance
I am using Audio from expo-av in react-native-expo.
I can run the audio using loadAsync method on Audio.sound contructor.
Although when I try to stop the voice it doesn't stop the voice.
Following is the minimalistic code snippet. Is this the correct way to stop the sound. I am not able to find the solution for this.
import React, {useState, useEffect} from 'react';
import { Button } from 'react-native';
import { Audio } from 'expo-av';
export default function App() {
const [audioStatus, setAudioStatus] = useState(false)
const sound = new Audio.Sound();
useEffect(()=>{
(async () => {
console.log('status', audioStatus)
if (audioStatus) {
await sound.loadAsync('https://www.soundhelix./examples/mp3/SoundHelix-Song-1.mp3')
try {
await sound.playAsync()
} catch (e) {
console.log(e)
}
}else {
await sound.stopAsync()
await sound.unloadAsync()
}
})()
},[audioStatus])
return (
<Button color={audioStatus ? 'red' : 'green'} title={'play'} onPress={()=>setAudioStatus(!audioStatus)} />
);
}
Thanks in Advance
Share Improve this question asked Nov 11, 2020 at 11:26 nikhil024nikhil024 4798 silver badges22 bronze badges1 Answer
Reset to default 6This is a React problem. Each time your ponent renders, the sound
variable is being reset to a new, not-yet-loaded Audio.Sound
object. Here, sound
should be part of the state of the ponent. You can change the line:
const sound = new Audio.Sound();
to
const [sound, setSound] = useState(new Audio.Sound());
and it will work.
Expo Snack
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745215488a4616994.html
评论列表(0条)