Update: I've made significant improvements to the module. Please refer to the documentation for the latest APIs.
I've open-sourced 'react-native-sound', a native module for playing sound files in React Native apps. It supports preloading and sound mixing with an audio player pool. The module is currently iOS-only, but an Android port is coming soon.
Installation
npm install react-native-sound --save
In XCode, right click Libraries. Click Add Files to "[Your project]". Navigate to node_modules/react-native-sound. Add the file RNSound.xcodeproj. In the project navigator, select your project. Click the build target. Click Build Phases. Expand Link Binary With Libraries. Click the plus button and add libRNSound.a under Workspace.
Usage example
Now you're ready to play sound clips in your React Native app. Just drop sound files in your XCode project and call the following APIs from JavaScript.
var Sound = require('react-native-sound');
Sound.enable(true); // Enable sound
Sound.prepare('tap.aac'); // Preload the sound file 'tap.aac'
Sound.play('tap.aac'); // Play the sound 'tap.aac'
Notes
- Sound.enable(true) must be called before playing any sound.
- Sound.prepare(...) preloads a sound file and prepares it for playback. If you do not call Sound.prepare(...) beforehand, Sound.play(...) will still work, but there might be a noticeable delay on the first call.
- You can make multiple Sound.play(...) calls at the same time. Under the hood, this module uses AVAudioSessionCategoryAmbient to mix sounds.
- The module wraps AVAudioPlayer which supports aac, aiff, mp3, wav etc. The full list of supported formats can be found at https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/MultimediaPG/UsingAudio/UsingAudio.html
Does this support looping?
ReplyDeleteYes, it does now.
DeleteYes, it does now.
DeleteNot yet. I'm planning to add looping/pausing/resuming in the next version. The API will be backward-incompatible, though.
ReplyDelete