How to Build an Music Player in React Native

August 17, 2020

How to Build an Music Player in React Native

App.js

import React ,{useEffect} from 'react';
import { View ,Pressable,Text} from 'react-native';
import TrackPlayer from 'react-native-track-player';
import { useTrackPlayerProgress } from 'react-native-track-player';
let track = [
   {
      id: '2',
      url:'https://cdn5.upload.solutions/b501ed97e72bb8a222e7da321f9c41a1/dfpnv/Mann%20Jaage-(Mr-Jatt.com).mp3',
      type: 'default',
      title: 'Bitto Boss (2012)',
      album: 'Bitto Boss (2012)',
      artist: 'Shahid Mallya',
      artwork: 'https://www.pagalworld.mobi/GpE34Kg9Gq/6810/thumb-bitto-boss-2012-300.jpg',
   },
   {
   id: '1',
   url:'https://pagalsongs.site/files/sfd3/1455/Kyon(PaglaSongs).mp3',
   type: 'default',
   title: 'Kyon',
   album: 'Kyon',
   artist: 'B Praak, Payal Dev',
   artwork: 'https://paglasongs.com/uploads/thumb/sft3/1455_4.jpg',
}
];
const App = () => {
  
   const { position, bufferedPosition, duration } = useTrackPlayerProgress();

   const trackPlayerInit = async () => {
      await TrackPlayer.setupPlayer({
          maxCacheSize:1048576,
      });
      return true;
   }
   useEffect(() => {
      trackPlayerInit();
      TrackPlayer.updateOptions({
         stopWithApp: true,
         alwaysPauseOnInterruption: true,
         capabilities: [
            TrackPlayer.CAPABILITY_PLAY,
            TrackPlayer.CAPABILITY_PAUSE,
            TrackPlayer.CAPABILITY_SEEK_TO,
            TrackPlayer.CAPABILITY_SKIP_TO_NEXT,
            TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS
        ],
        compactCapabilities: [
            TrackPlayer.CAPABILITY_PLAY,
            TrackPlayer.CAPABILITY_PAUSE,
            TrackPlayer.CAPABILITY_SEEK_TO,
            TrackPlayer.CAPABILITY_SKIP_TO_NEXT,
            TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS
        ],
        notificationCapabilities: [
            TrackPlayer.CAPABILITY_PLAY,
            TrackPlayer.CAPABILITY_PAUSE,
            TrackPlayer.CAPABILITY_SEEK_TO,
            TrackPlayer.CAPABILITY_SKIP_TO_NEXT,
            TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS
        ]

       });
   }, [])
    


    const onPressFunction=()=>{
      TrackPlayer.add(track)
      TrackPlayer.play();
    }
      const onPressStop=()=>{
         TrackPlayer.stop();
      }
      const onPressPause=()=>{
         TrackPlayer.pause();
      }

  return <View style={{backgroundColor:'white',flex:1,justifyContent:'center',alignItems:'center'}}>
            <Pressable onPress={onPressFunction} style={{backgroundColor:'#6200ee',padding:15,margin: 10}}>
               <Text style={{color:'white',width:200,fontWeight:'bold',fontSize:16,textAlign:'center'}}>Play</Text>
            </Pressable>

            <Pressable onPress={onPressStop} style={{backgroundColor:'#000',padding:15,margin: 10}}>
               <Text style={{color:'white',width:200,fontWeight:'bold',fontSize:16,textAlign:'center'}}>Stop</Text>
            </Pressable>

            <Pressable onPress={onPressPause} style={{backgroundColor:'orange',padding:15,margin: 10}}>
               <Text style={{color:'white',width:200,fontWeight:'bold',fontSize:16,textAlign:'center'}}>Pause</Text>
            </Pressable>
            <Pressable onPress={()=>TrackPlayer.seekTo(12.5)} style={{backgroundColor:'orange',padding:15,margin: 10}}>
               <Text style={{color:'white',width:200,fontWeight:'bold',fontSize:16,textAlign:'center'}}>Seek</Text>
            </Pressable>
            <Pressable onPress={()=>TrackPlayer.setVolume(0.5)} style={{backgroundColor:'orange',padding:15,margin: 10}}>
               <Text style={{color:'white',width:200,fontWeight:'bold',fontSize:16,textAlign:'center'}}>Volume</Text>
            </Pressable>

            <View>
      <Text>Track progress: {position} seconds out of {duration} total</Text>
      <Text>Buffered progress: {bufferedPosition} seconds buffered out of {duration} total</Text>
    </View>
        </View>
}

export default App;

Root index.js

/**
 * @format
 */

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import TrackPlayer from 'react-native-track-player';
AppRegistry.registerComponent(appName, () => App);
TrackPlayer.registerPlaybackService(() => require('./service.js'));

service.js for Handle playback services

import TrackPlayer from 'react-native-track-player';

module.exports = async function() {

  TrackPlayer.addEventListener('remote-play', () => {
    TrackPlayer.play();
  })

  TrackPlayer.addEventListener('remote-pause', () => {
    TrackPlayer.pause();
  })

  TrackPlayer.addEventListener('remote-next', async () => {
    TrackPlayer.skipToNext();
  })

  TrackPlayer.addEventListener('remote-duck', async () => {
    TrackPlayer.pause();
  })

  TrackPlayer.addEventListener('remote-previous', async () => {
    TrackPlayer.skipToPrevious();
  })
};

Written by Manoj Bhardwaj who lives and works in Mohali Punjab (India). My stackoverflow