React Native - Expo Audio 停止所有声音 [英] React Native - Expo Audio stop all sounds

查看:42
本文介绍了React Native - Expo Audio 停止所有声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Expo Audio 从列表.

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);
    }
}

我从用 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.

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

推荐答案

我想我应该在构造函数中创建播放对象并使用 unloadAsync()

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)
        }
    }

完整文档位于 AV - Expo 文档

这篇关于React Native - Expo Audio 停止所有声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆