react-native-audio-toolkit, isPlaying is not working

Viewed 1809
import React from "react";
import { Player } from "@react-native-community/audio-toolkit"; 


export default class RNAudiotoolkit extends React.Component {
componentDidMount(){
    new Player("some_audio_file.mp3").play();
    console.log(Player.isPlaying);
}
}

Above is the minimum code I've whittled down to, the audio track does play but, console.log(Player.isPlaying) always returns "false" but the audio file is running. Any input on why this isn't working. I can only suspect it has something to do with MediaStates, but have unsuccessfully gotten anything to work. If you have experience with this package your input is greatly appreciated.

documentation: https://github.com/react-native-community/react-native-audio-toolkit/blob/master/docs/API.md

2 Answers

Edit: Fixed and tested; answer is a combination of my original and mAhMoUdDaFeR's answer.

If you look above the documentation for the play method, you will see the documentation for prepare(Function callback). In it, it states:

...Otherwise the file is prepared when calling play() which may result in a small delay.

This means that if you check the .isPlaying property immediately after calling play() like you are doing, it is not guaranteed that the file is actually playing by time your console.log(Player.isPlaying) executes.

There is also the second issue that .isPlaying is not a static property on the Player class despite how it appears in the docs. It is actually a property of the Player instance that you need to create to play an audio file.

If you want to see that .isPlaying is indeed working correctly, one potential check is to run your code in a callback function passed into .play() as the docs show:

play(Function ?callback)

Start playback.

If callback is given, it is called when playback has started.

So a simple example would be to write your example code like this (saving the created instance and then logging in a callback):

componentDidMount(){
    const p = new Player("some_audio_file.mp3").play(() => console.log('in callback', p.isPlaying));
    console.log('immediately after play', p.isPlaying);
}

I created a new project to test this and if you run the above code, you'll see the following printed out illustrating the issue:

immediately after play false
in callback true

isPlaying is not a static method in the component Player, so you can't use Player.isPlaying, you can get isPlaying from the created instance (object) of this Player.

Try keeping a reference of the player object and then accessing its children:

this.player = new Player("some_audio_file.mp3").play()

and then log:

console.log(this.player.isPlaying)

Related