To play a sound, first enable playback in silence mode (essential for iOS) using Sound.setCategory('Playback'). Then, instantiate a new Sound object by providing the filename and the source type (e.g., Sound.MAIN_BUNDLE).
Note: Always call release() on your sound instance when it is no longer needed to free up resources.
import Sound from "react-native-sound";
// Enable playback in silence mode (important for iOS)
Sound.setCategory("Playback");
// Load a sound file from the app bundle
const whoosh = new Sound("whoosh.mp3", Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log("Failed to load the sound", error);
return;
}
// Sound loaded successfully
console.log("Duration:", whoosh.getDuration(), "seconds");
console.log("Channels:", whoosh.getNumberOfChannels());
// Play the sound
whoosh.play((success) => {
if (success) {
console.log("Successfully finished playing");
} else {
console.log("Playback failed due to audio decoding errors");
}
});
});
// Audio controls
whoosh.setVolume(0.5); // 50% volume
whoosh.setPan(1); // Full right stereo
whoosh.setNumberOfLoops(-1); // Loop indefinitely
// Get current properties
console.log("Volume:", whoosh.getVolume());
console.log("Pan:", whoosh.getPan());
console.log("Loops:", whoosh.getNumberOfLoops());
// Seek to specific time
whoosh.setCurrentTime(2.5);
// Get current playback position
whoosh.getCurrentTime((seconds) => {
console.log("Current time:", seconds);
});
// Control playback
whoosh.pause(); // Pause playback
whoosh.stop(() => {
// Stop and rewind
whoosh.play(); // Play from beginning
});
// Always release resources when done
whoosh.release();