本机声音反应停止所有声音

时间:2018-04-02 23:48:56

标签: javascript reactjs react-native react-native-sound

我想从列表中播放长音频文件,首次点击下载文件,所有下一个点击播放音频。但问题是当播放一个文件然后点击另一个文件时,第一个文件仍在播放,下一个文件也在播放。当我点击任何列表项时,有没有办法停止所有当前播放的文件?

 onPressHandler = (file, title) => {
    let name = file.substring(file.lastIndexOf("/") + 1);

    RNFetchBlob.fs.exists(`/storage/sdcard0/Android/data/com.myapp/files/Download/${name}.mp3`)
        .then((exist) => {
            if (exist) {
                /* I want to stop all playing audios here */
                var whoosh = new Sound(`/storage/sdcard0/Android/data/com.myapp/files/Download/${name}.mp3`, '', (error) => {
                    if (error) {
                        alert('failed to load the sound', error);
                        return;
                    }
                    alert('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels());
                    alert(whoosh.isLoaded());

                    whoosh.play((success) => {
                        if (success) {
                            alert('successfully finished playing');
                        } else {
                            alert('playback failed due to audio decoding errors');
                            whoosh.reset();
                        }
                    });
                });
            } else {
                const url = `http://myresourcesite/${file}.mp3`;
                const headers = {};
                const config = {
                    downloadTitle: name,
                    downloadDescription: 'Downloading ...',
                    saveAsName: `${name}.mp3`,
                    allowedInRoaming: true,
                    allowedInMetered: true,
                    showInDownloads: true
                };
                downloadManager.download(url, headers, config).then((response) => {
                    alert('Download success!');
                }).catch(err => {
                    alert('Download failed!');
                });
            }
        })
        .catch(() => {
            alert('error has occured');
        });
}

1 个答案:

答案 0 :(得分:0)

我认为没有stopAll()函数。您需要跟踪创建的实例。我使用一个全局变量。通过某种逻辑,我可以确保一次只播放一种声音。

  • 创建新的声音对象时,请将其分配给全局变量。
  • 在创建新的声音对象之前,请在全局实例上停止声音
  • 为首次点击在全局变量上添加空检查
var whoosh = new Sound(`/storage/sdcard0/Android/data/com.myapp/files/Download/${name}.mp3`, '', (error) => {
    if (error) {
        alert('failed to load the sound', error);
        return;
    }
    if (global.sound) global.sound.stop();
    global.sound = whoosh;
    whoosh.play( success => { console.log('Playing') } );
}

人们认为JS中的全局变量不好。如果您滥用是。但是在这种情况下,它确实是一个全局对象,并且使用它没有任何错误。这不是滥用。