Giter VIP home page Giter VIP logo

react-native-sound-player's Introduction

react-native-sound-player

Play audio files, stream audio from URL, using ReactNative.

Installation

1. yarn or npm

    // yarn
    yarn add react-native-sound-player
    // or npm
    npm install --save react-native-sound-player

2. Link

For RN >= 0.60 you can skip this step.

    react-native link react-native-sound-player

Usage

Play sound with file name and type

  1. Add sound files to iOS/Android.
  • On iOS, drag and drop sound file into project in Xcode. Remember to check "Copy items if needed" option and "Add to targets".
  • On Android, put sound files in {project_root}/android/app/src/main/res/raw/. Just create the folder if it doesn't exist.
  1. Import the library and call the playSoundFile(fileName, fileType) function:
import SoundPlayer from 'react-native-sound-player'

try {
    // play the file tone.mp3
    SoundPlayer.playSoundFile('tone', 'mp3')
    // or play from url
    SoundPlayer.playUrl('https://example.com/music.mp3')
} catch (e) {
    console.log(`cannot play the sound file`, e)
}

Please note that the device can still go to sleep (screen goes off) while audio is playing. When this happens, the audio will stop playing. To prevent this, you can use something like react-native-keep-awake. Or alternatively, for iOS, you can add a Background Mode of Audio, AirPlay, and Picture in Picture in XCode. To do this, select your application from Targets, then click on Signing & Capabilities and add Background Modes. once the options for it appear on your Signing & Capabilities page select the checkbox with Audio, AirPlay, and Picture in Picture. This will allow the application to continue playing audio when the app is in the background and even when the device is locked.

Functions

playSoundFile(fileName: string, fileType: string)

Play the sound file named fileName with file type fileType.

playSoundFileWithDelay(fileName: string, fileType: string, delay: number) - iOS Only

Play the sound file named fileName with file type fileType after a a delay of delay in seconds from the current device time.

loadSoundFile(fileName: string, fileType: string)

Load the sound file named fileName with file type fileType, without playing it. This is useful when you want to play a large file, which can be slow to mount, and have precise control on when the sound is played. This can also be used in combination with getInfo() to get audio file duration without playing it. You should subscribe to the onFinishedLoading event to get notified when the file is loaded.

playUrl(url: string)

Play the audio from url. Supported formats are:

loadUrl(url: string)

Load the audio from the given url without playing it. You can then play the audio by calling play(). This might be useful when you find the delay between calling playUrl() and the sound actually starts playing is too much.

addEventListener(callback: (object: ResultObject) => SubscriptionObject)

Subscribe to any event. Returns a subscription object. Subscriptions created by this function cannot be removed by calling unmount(). You NEED to call yourSubscriptionObject.remove() when you no longer need this event listener or whenever your component unmounts.

Supported events are:

  1. FinishedLoading
  2. FinishedPlaying
  3. FinishedLoadingURL
  4. FinishedLoadingFile
  // Example
  ...
  // Create instance variable(s) to store your subscriptions in your class
  _onFinishedPlayingSubscription = null
  _onFinishedLoadingSubscription = null
  _onFinishedLoadingFileSubscription = null
  _onFinishedLoadingURLSubscription = null

  // Subscribe to event(s) you want when component mounted
  componentDidMount() {
    _onFinishedPlayingSubscription = SoundPlayer.addEventListener('FinishedPlaying', ({ success }) => {
      console.log('finished playing', success)
    })
    _onFinishedLoadingSubscription = SoundPlayer.addEventListener('FinishedLoading', ({ success }) => {
      console.log('finished loading', success)
    })
    _onFinishedLoadingFileSubscription = SoundPlayer.addEventListener('FinishedLoadingFile', ({ success, name, type }) => {
      console.log('finished loading file', success, name, type)
    })
    _onFinishedLoadingURLSubscription = SoundPlayer.addEventListener('FinishedLoadingURL', ({ success, url }) => {
      console.log('finished loading url', success, url)
    })
  }

  // Remove all the subscriptions when component will unmount
  componentWillUnmount() {
    _onFinishedPlayingSubscription.remove()
    _onFinishedLoadingSubscription.remove()
    _onFinishedLoadingURLSubscription.remove()
    _onFinishedLoadingFileSubscription.remove()
  }
  ...

onFinishedPlaying(callback: (success: boolean) => any)

Subscribe to the "finished playing" event. The callback function is called whenever a file is finished playing. This function will be deprecated soon, please use addEventListener above.

onFinishedLoading(callback: (success: boolean) => any)

Subscribe to the "finished loading" event. The callback function is called whenever a file is finished loading, i.e. the file is ready to be play(), resume(), getInfo(), etc. This function will be deprecated soon, please use addEventListener above.

unmount()

Unsubscribe the "finished playing" and "finished loading" event. This function will be deprecated soon, please use addEventListener and remove your own listener by calling yourSubscriptionObject.remove().

play()

Play the loaded sound file. This function is the same as resume().

pause()

Pause the currently playing file.

resume()

Resume from pause and continue playing the same file. This function is the same as play().

stop()

Stop playing, call playSound(fileName: string, fileType: string) to start playing again.

seek(seconds: number)

Seek to seconds of the currently playing file.

setSpeaker(on: boolean)

Overwrite default audio output to speaker, which forces playUrl() function to play from speaker.

setMixAudio(on: boolean)

Only available on iOS. If you set this option, your audio will be mixed with audio playing in background apps, such as the Music app.

setVolume(volume: number)

Set the volume of the current player. This does not change the volume of the device.

setNumberOfLoops(volume: number) - iOS Only

Set the number of loops. A negative value will loop indefinitely until the stop() command is called.

getInfo() => Promise<{currentTime: number, duration: number}>

Get the currentTime and duration of the currently mounted audio media. This function returns a promise which resolves to an Object containing currentTime and duration properties.

// Example
...
  playSong() {
    try {
      SoundPlayer.playSoundFile('engagementParty', 'm4a')
    } catch (e) {
      alert('Cannot play the file')
      console.log('cannot play the song file', e)
    }
  }

  async getInfo() { // You need the keyword `async`
    try {
      const info = await SoundPlayer.getInfo() // Also, you need to await this because it is async
      console.log('getInfo', info) // {duration: 12.416, currentTime: 7.691}
    } catch (e) {
      console.log('There is no song playing', e)
    }
  }

  onPressPlayButton() {
    this.playSong()
    this.getInfo()
  }

...

react-native-sound-player's People

Contributors

ahm1371ahm avatar assertchris avatar brianh2 avatar egrimstad avatar j-5-s avatar jefflewis avatar johnsonsu avatar jonasb avatar lahmud avatar mbatroukh avatar mstrk avatar puposdc avatar rcidt avatar respectthecode avatar salimhb avatar snwstaff avatar tobidevloft avatar victor36max avatar zaenalarsy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-native-sound-player's Issues

Not working on react-native version "0.44.0"

Hello guys I try to follow the instruction above but it seems that it is not working. it showing me this error

undefined is not an object(eveluating 'RNSoundPlayer.playSoundFile')
Im running it on android
using react-native version: "version": "0.44.0"

Running multiple tracks at a time in react native using sound player module

Describe the bug
I'm using react-native-sound-player in my application, I want to play the multiple tracks at a time, but this module only allows me to play a song at a time.
Is there any way to do this using this module.
Expected behavior
Play the multiple songs at a time

Platform (please complete the following information):

  • Android

react-native 0.60.0, isAndroid of undefined, CocoaPods could not find compatible versions for pod "React/Core"

have:

    "react": "16.8.6",
    "react-native": "0.60.0",
    "react-native-sound": "0.10.12",

have done npm i then running a project but receiving the error:
Cannot read property 'IsAndroid' of undefined
consoling inside of file 'sound.js' of package
Screen Shot 2019-07-05 at 4 42 52 PM
and this is true, there are no RNSound
image

pod install returns me:

[!] CocoaPods could not find compatible versions for pod "React/Core":
  In Podfile:
    RNSound (from `/Users/antongoncharov/Development/hearingapp/node_modules/react-native-sound`) was resolved to 0.10.12, which depends on
      React/Core

None of your spec sources contains a spec satisfying the dependency: `React/Core`.

You have either:
 * out-of-date source repos which you can update with `pod repo update` or with `pod install --repo-update`.
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.

Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by default.

Playing online audio files

Are there plans for updates on playing online audio files from network? I really like this library, it's super easy to implement, and this feature would make it a lot better

Onseek backward not working and playing audio too

Thanks for the great library. But, On seek forward is working fine, But, Rewind(back) not playing.

I am using slider for forward and rewind the audio.

SoundPlayer.seek(sliderValue);
SoundPlayer.play();

Any suggestions?

Can't play from locally downloaded file

Hi,

I have a file downloaded this mp3: https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3 using react-native-fs into MAIN_BUNDLE on an IOS emulator. I can verify the file is there and I can play it with any audio player on my Mac /Library/Developer/CoreSimulator/Devices/594B5EDF-5E73-4040-9236-2DA23A1BAC86/data/Containers/Data/Application/A60A1E1B-EBD9-4A59-9B90-4A3148D68D7D/Documents/mpthreetest.mp3

Yet, I get this error when I run:

SoundPlayer.playSoundFile(filename, 'mp3');

image

Looking at RNSoundPlayer.m I can see that the default location is mainBundle. I tried with many files mp4, ogg but the same is happening.

When I play the URL directly with

SoundPlayer.playUrl(url)

it plays without a problem, but I need to download files first before playing it to make sure the file is available offline.

Any help would be appreciated!

Playing 2.track is not overlapping

So in my app I use musics like a radio and, sometimes there is effects like 2-3 seconds. But when radio is open and when I try to play sound effect, its not overlapping?.. instead its closing first music .. what I can do about it?

"Native module cannot be null"

Describe the bug
After upgrading to RN 0.60 an invariant error is called on NativeEventEmitter -> "Native module cannot be null".

To Reproduce
Steps to reproduce the behavior:

  1. Just import react-native-sound-player in any file.

Platform (please complete the following information):

  • OS: IOS

Additional context

  • This only happens on ios, android is working as expected.
  • Tested on Android 9.x, and iPhone 5s, both real devices.
  • "react-native-sound-player": "0.10.0"

Proposal: Allow seeking

We currently have half of what we need to have a seek-able progress bar (the meta info for how long a song is and what the current position is), but no way to move to somewhere in the middle of the song.

Proposal: tag a release

I've writing about using this library, but without a tagged release I have to tell readers to depend on dev master. It would be awesome if there was a tag I could point them to (even if it was a 0.1.0 tag)...

Audio not playing on iOS

Hi,
Thanks for your library, but I have a problem. Android works well, but on iOS (using iOS 12.1 and react-native 0.57.4) it doesn't work. The callback onFinishedPlaying is getting fired even if no sound comes out from the device.
Here's the screen that shows where I've placed the mp3.

immagine

It doesn't work even if I load a sound from the web.
Also, it doesn't throw any error.

Thanks again,
Nicholas

Android - cannot play locally downloaded file

Is there a way to play songs from somewhere other than the main bundle location (eg. external storage or a documents folder) ?

It's a similar question to #10 - but wondering if there is an Android implementation for the fallback mentioned in the solution?

PS. Thank you to you and all contributors for this library, very handy!

How to keep move slider value according to audio play duration

Thanks for the good library. We are using this, But, For the progress of the audio, We are showing Slider in UI. But, We have to keep move the progress bar status according to audio play.

Is there any method to get keep information about audio status?
And how to track buffering audio state? Is there any delegate method?
Also it is taking time to play URL like 5 to 10 seconds for online streaming, How to get is preparing play kind states?

Multiple event listeners

Hey, first of all great library it's the only one which works without any problems for us!

I've got a question, why is it not possible to add as many event listeners as I'd like? You're deliberately killing off old listeners here:

if (_finishedPlayingListener) {
_finishedPlayingListener.remove()
_finishedPlayingListener = undefined
}

I am using the sound player all over my app (mostly with playUrl though) and would love to have more fine grained control than a 'singleton callback'.

In my opinion it would be great to have something similar as the DOM event listener system. What do you think?

Roughly like this:

SoundPlayer.playUrl('https://example.com/some.mp3')

SoundPlayer.addEventListener('URLFinishedLoading', url => {})
SoundPlayer.addEventListener('FileFinishedLoading', (name, type) => {})

I am not sure if this is covering all cases but I think it would be a great improvement.

[iOS] Problem listening FinishedLoading

It seems the index.js in the package has not registered the FinishedLoading for iOS. I got this warning Sending "FinishedLoading" with no listeners registered.

Show currentTime & duration

How can I change the state inside the getInfo()-method? Insteed of showing duration:.... currenttime:..., I just want to get currentTime in the state. This is my code. this.setState({seconds: info}) doesnt work..

 async getInfo() {
    try {
      const info = await SoundPlayer.getInfo();
      this.setState({seconds: info})
      console.log("info", info);
    } catch (e) {
      console.log("There is no song playing", e);
    }
  }

Import error

Hey! Thanks for developing this module, will be using it in an upcoming project.

This is probably a silly error but I've tried following the installation steps but I'm stuck at importing this package.

I opened it on Android Studio to check if it had been imported correctly, and that seems to be an issue.
It's red at the import statement, and I don't see the corresponding folder on the left side section in the project structure.

I followed the steps of installing using NPM & running react-native link.

Here are some screenshots:
image
image

This is the error I get when I run react-native run-android
image

playUrl(url) not starting playback on iOS

When I call playUrl(url), the sound never starts playing. Originally I thought my iOS simulator was just not working correctly, but I added the SoundPlayer.onFinishedPlaying() event listener to my componentWillMount() method, and the code inside was never run.

The catch() function isn't called either so there is no error.

Proposal: keep awake while playing

It would be neat if there was an option to keep the device's screen from switch off while playing music. Currently, I am using https://github.com/corbt/react-native-keep-awake to do this. Perhaps it's not the sort of thing you want this library to do (and I completely understand that). I'd suggest at least documenting that the screen will still go off, and suggesting what can be done to prevent that...

Ability to loop?

Hi! I'm currently using react-native-sound but I'm finding it really hard to work with as it's a lot of bugs and I'm thinking about switching over to this one. Is there any way to add a way to loop sounds? I want to have some background music that loops in the background.

Thanks in advance!

Can't play any track..

My codes :
import SoundPlayer from 'react-native-sound-player';

playTrack(){
try {
SoundPlayer.playSoundFile('free', 'mp3');
} catch (e) {
console.log(cannot play the sound file, e);
}
}

When I call this function I get error in console log;

"cannot play the sound file TypeError: Cannot read property 'playSoundFile' of undefined"

What I should do ?.. I checked all options again and again, I linked correctly, mp3 files are located in raw.. I dont know what else I can do .

Edit: I run react-native run-android to compile the project again now its not giving error but I dont hear any sounds..

setVolume for soundPlayer

How I can setVolume for soundPlayer while I playing an Song. example: "soundPlayer.setVolume(0.5)"

error when await SoundPlayer.getInfo();

I'm trying to get info for a sound located at:

https://api.twilio.com/2010-04-01/Accounts/AC59f045f6bbe657c72a2bfbdf7736b5cd/Recordings/RE8d57ef4c537183172c3c819fcbff6b66.mp3

for some reason I received the following error:

RCTJSONStringify() encountered the following error: Invalid number value (NaN) in JSON write

playSound is not a function.

@omkarsk98, you can use the playSound('/pathToTheFileYouWantToPlay/filename', 'filetype') function with the path to the file and its type. You need to get the path using react-native-fs or whatever you used to download the file.

I will lock this conversation, please create an issue if you have further questions.

Originally posted by @johnsonsu in #37 (comment)

It returns playSound is not a function when using the above method. It does not show this function even in the module. Is there any alternative? Please help.

Delay between FinishedLoadingURL and actually playing the sound

I want to show a bar of the current progress of playing my file from a URL:

const listener = SoundPlayer.addEventListener(
  'FinishedLoadingURL',
  async result => {
    const info = await SoundPlayer.getInfo()

    Animated.timing(playingAnimationValue.current, {
      toValue: 100,
      duration: info.duration * 1000
    }).start()
  }
)

Unfortunately there's a delay between FinishedLoadingURL and the file actually being played. How can I resolve this without having an artificial delay?
Thanks!

edit: Seems to be more a problem on iOS than Android

AAPT2: invalid package name

I am getting this error for the verifyReleaseResources Gradle task after upgrading to

  • react-native 0.57.1
  • Android build tools 27.0.3
  • Gradle 4.4

AAPT: error: attribute 'package' in tag is not a valid Android package name: 'rnsoundplayer'.

Task :react-native-sound-player:verifyReleaseResources FAILED

Error generating signed apk.

React Native version 0.59.8

Steps to reproduce.

  1. I followed the instruction.
  • yarn add react-native-sound-player
  • react-native link react-native-sound-player
  • followed the basic sound playing
  1. Generate signed apk.
  • cd android && ./gradlew assembleRelease

Build fails and shows this message

Screen Shot 2019-05-14 at 5 43 50 PM

Feature Request: onStartedPlaying

Hi @johnsonsu

I am currently working at a project where it is very important to synchronize a particular action with a sound effect. Now I discovered that there sometimes is a slight delay between the playSoundFile call and when I can actually hear the sound. I believe this might be because the system needs some time to load the sound first..?

However, a great solution for this would be to have a callback similar to onFinishedPlaying that is called as soon as the sound is loaded and actually started playing. Would it be possible to introduce a new onStartedPlaying callback for this purpose?

Cheers

[BUG]

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Write a function play from Url
    export function playSoundEffect (soundUrl, isSystemMusic) { const callback = () => { AudioPlayer.play() } if (isSystemMusic) { AudioPlayer.prepareWithFile(soundUrl, 'mp3', callback) } }

Expected behavior
It can play in IOS and Android but
It only cann't play in Android 6.0 RIO-AL00 and get Error like This

attempt to invoke virtual method 'void android.media.Mediaplayer.setOnCompletionListener (android.media.MediaPlayer$OnCompletionListener)'
on a null object reference
- playUrl
RNSoundPlayerModule.java: 56
- inkove
Method.java

Platform (please complete the following information):

  • react-native: 0.55.4
  • react: 16.0.0
  • android: 6.0.1
  • device: HUAWEI RIO-AL00

Additional context
Add any other context about the problem here.

Important typo in FinishedPlyaing in README

In README file, under addEventListener section there's an error:

_onFinishedPlayingSubscription = SoundPlayer.addEventListener('**FinishedPlyaing**', ({ success }) => {

Instead of:

_onFinishedPlayingSubscription = SoundPlayer.addEventListener('**FinishedPlaying**', ({ success }) => {

This caused a bug from my quick copy/paste =)

Link iOS package

How can I link this package to iOS manually or using cocopod?

Native module cannot be null.

When I run my app I get this error:

Native module cannot be null.

I'm using React 16.0.0-alpha.12 because I'm using Expo.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.