React Native - Expo Audio 停止所有声音

Eve*_*lyn 5 audio-player react-native expo

我正在使用Expo Audio从列表中播放一些简短的声音。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我从一个呈现的列表中调用 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)

    ...
    }
Run Code Online (Sandbox Code Playgroud)

声音播放正常,但是当我选择列表中的下一项时,之前的声音并没有停止。所以如果我连续触摸一堆,就会同时播放一堆声音。

如何停止所有当前播放的声音?

Eve*_*lyn 7

我想我应该在构造函数中创建播放对象并使用 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)
        }
    }
Run Code Online (Sandbox Code Playgroud)

完整文档可在AV - Expo 文档中找到