React Native - Expo Audio stop all sounds

半世苍凉 提交于 2019-12-07 09:34:00

问题


I am using Expo Audio to play some short sounds from a list.

async playAudio(file) {

    try {
        await Audio.setIsEnabledAsync(true);
        const sound = new Audio.Sound();
        await sound.loadAsync(file);
        await sound.playAsync(); 
    } catch(error) {
      console.error(error);
    }
}

Which I'm calling from a list rendered with list.map()

renderTheList = (item, i) => {
    return (
        <View key={i}> 
            <TouchableOpacity onPress={ () => { this.onAudioSelected(item.audio) }}>
            </TouchableOpacity>
        </View>
    )
}

onAudioSelected(audio) {
    // Audio.clearSounds() <-- something like this
    playAudio(audio)

    ...
    }

The sounds play fine, but when I select the next item in the list, the previous sound does not stop. So if I touch a bunch in a row, a bunch of sounds play at once.

How can I stop all currently playing sounds?


回答1:


I figured out that I should create the playback object in the constructor and use unloadAsync()

constructor(props)
    {
      super(props);

      this.audioPlayer = new Audio.Sound();

    }

    playSound = async () => {
        try {
          await this.audioPlayer.unloadAsync()
          await this.audioPlayer.loadAsync(require("../soundfile.mp3"));
          await this.audioPlayer.playAsync();
        } catch (err) {
          console.warn("Couldn't Play audio", err)
        }
    }

The full documentation is found at AV - Expo Documentation



来源:https://stackoverflow.com/questions/50292035/react-native-expo-audio-stop-all-sounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!