How to show media controls in lockscreen/background state in react-native

Viewed 2560

I am doing react-native project. And I am playing some network url's which are getting from server. It is single player.

So, To play audio, I am using following library.

https://www.npmjs.com/package/react-native-sound-player

And I have customised the player controls according to my UI. Audio playing well and also I have enabled playing audio in background mode in settings.

But, If I go to foreground/lockscreen state, Audio playing but, Media controls are not showing.

I am new to react-native, Do I need to customise media controls for background/lockscreen state too? Or anything do I need to do to achieve this?

  componentDidMount() {
  const { audioURL } = this.state;
  SoundPlayer.playUrl(audioURL);
  }

    playPauseHandler = () => {
    const {
      paused, currentDuration, currentTime, audioSelectedIndex,
    } = this.state;
    console.log('currentDuration', currentDuration);
    console.log('currentTime', currentTime);
    this.getInfo();

    if (paused === true) {
      SoundPlayer.play();
      this.setState({ paused: !paused });
    } else {
      SoundPlayer.pause();
      this.setState({ paused: !paused });
    }
  }

       render() {

          return (

            <View style={styles.audioPlayerContainer}>
              <Image
                style={styles.podcastImage}
                source={{ uri: podcastImage }}
              />
              {/* <Text> {playTime} </Text> */}

              <View style={styles.sliderCloseButtonContainer}>
                <Slider
                  maximumValue={totalLength}
                  step={1}
                  value={currentTime}
                  onSlidingComplete={value => this.onValueChange(value)}
                  style={styles.slider}
                  thumbTintColor=“blue”
                // onSeek={this.seek.bind(this)}
                  trackLength={totalLength}
                // onSlidingStart={() => this.setState({ paused: true })}
                />
              </View>
              <View style={styles.stylesContainer}>
                  {title}
                </TextTicker>
                <TouchableWithoutFeedback onPress={this.playPauseHandler}>
                  <View style={styles.playButton}>
                    <Image source={paused ? res.images.play : 
                   res.images.pause} />
                  </View>
                </TouchableWithoutFeedback>
              </View>
            </View>
            )
            }
         );
      }

enter image description here

Any suggestions?

2 Answers

Used below simple solution:

Install below dependency:-

With Yarn:

yarn add react-native-music-control

or with NPM:

npm install react-native-music-control --save

go to your file :

import MusicControl from 'react-native-music-control';
import { Command } from 'react-native-music-control';


componentDidMount() {
    MusicControl.enableBackgroundMode(true);
    MusicControl.on(Command.play, () => {
        this.playAudioNow();
    })
    MusicControl.on(Command.stop, () => {
        this.pauseAudioRecording();
    })
    MusicControl.enableControl('play', true)
    MusicControl.enableControl('pause', true)
    MusicControl.enableControl('stop', true)
}


playAudioNow = () => {
    const { currentItem } = this.state;
    if (this.state.pauseRecording) {
        this.setState({ startRec: true, pauseRecording: false });
        SoundPlayer.resume();
    } else {
        let soundURI: any = currentItem && currentItem.audioUrl ? currentItem.audioUrl : currentItem.uri ? currentItem.uri : currentItem;
        this.setState({ startRec: true });
        this.playSoundFile(soundURI, currentItem);
    }
};



pauseAudioRecording = () => {
    this.setState({
        pauseRecording: true
    });
    SoundPlayer.pause();
};


setupBackgroundMusicControl = () => {
    MusicControl.setNowPlaying({
        title: 'Test',
        artwork: 'https://www.flaticon.com/premium-icon/mic_2882867', // URL or RN's image require()
        // duration: this.state.recordingfileTotalDuration, // (Seconds)

        // description: '', // Android Only
        // color: 0xffffff, // Android Only - Notification Color
        // colorized: true, // Android 8+ Only - Notification Color extracted from the artwork. Set to false to use the color property instead
        // date: '1983-01-02T00:00:00Z', // Release Date (RFC 3339) - Android Only
        // rating: 84, // Android Only (Boolean or Number depending on the type)
        // notificationIcon: 'my_custom_icon', // Android Only (String), Android Drawable resource name for a custom notification icon
        isLiveStream: true, // iOS Only (Boolean), Show or hide Live Indicator instead of seekbar on lock screen for live streams. Default value is false.
    })
}


stopMusicControl = () => {
            MusicControl.resetNowPlaying();
            SoundPlayer.stop();
}
Related