Home Reference Source

src/utils/SoundUtils.js

/**
 * Utils function for playing and stopping sounds
 */

import SoundPlayer from 'react-native-sound-player';

/**
 * Plays the .wav soundfile corresponding to the filename.
 * @param {string} filename - name of file that is to be played
 */
function playSound(filename) {
    //Different way depending on OS
    if (Platform.OS === 'ios') iosPlaySound(filename); //local method
    else {
        try {
            SoundPlayer.playSoundFile(filename, 'wav');
        } catch (e) {
            console.log(`Cannot play the sound file`, e);
        }
    }
}

/**
 * Stops the currently playing sound.
 */
function stopSound() {
    SoundPlayer.stop();
}

/**
 * Preferred way of playing sound on ios
 * @param {string} filename - name of file that is to be played
 */
function iosPlaySound(filename) {
    SoundPlayer.addEventListener('FinishedLoadingFile', ({success}) => {
        if (success) SoundPlayer.play();
    });
    SoundPlayer.loadSoundFile(filename, 'wav');
}
export {playSound, stopSound, iosPlaySound};