-
Install the Required Packages:
First, make sure you install the required packages:
npm install react-native-track-player
Or, if you're using Yarn:
yarn add react-native-track-player
-
Linking the Library:
For React Native 0.60 and above, autolinking should take care of this for you. However, for older versions, you may need to link the library manually:
react-native link react-native-track-player
-
Configure Track Player:
You will need to configure the track player in your application. This is usually done in a separate file (e.g., TrackPlayerService.js).
// TrackPlayerService.js
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-stop', () => {
TrackPlayer.stop();
});
// Add other remote event handlers as needed
};
-
Set Up the Audio Files:
Ensure your MP3 files are placed in the src/assets/audio directory. For example:
src/assets/audio/song1.mp3
src/assets/audio/song2.mp3
-
Load and Play Audio:
You can load and play the audio files as follows:
import React, { useEffect } from 'react';
import { View, Button } from 'react-native';
import TrackPlayer, { Capability } from 'react-native-track-player';
import TrackPlayerService from './TrackPlayerService'; // Adjust the path as needed
const App = () => {
useEffect(() => {
// Initialize the Track Player
TrackPlayer.setupPlayer().then(async () => {
await TrackPlayer.updateOptions({
stopWithApp: true,
capabilities: [Capability.Play, Capability.Pause, Capability.Stop],
});
// Add a track
await TrackPlayer.add({
id: 'trackId', // You can use any unique id
url: require('./src/assets/audio/song1.mp3'), // Adjust the path as needed
title: 'Song Title',
artist: 'Artist Name',
artwork: require('./src/assets/audio/artwork.png'), // Optional artwork
});
});
// Clean up the player on unmount
return () => {
TrackPlayer.destroy();
};
}, []);
const playTrack = () => {
TrackPlayer.play();
};
const pauseTrack = () => {
TrackPlayer.pause();
};
const stopTrack = () => {
TrackPlayer.stop();
};
return (
<View>
<Button title="Play" onPress={playTrack} />
<Button title="Pause" onPress={pauseTrack} />
<Button title="Stop" onPress={stopTrack} />
</View>
);
};
export default App;
-
Additional Configuration:
Depending on your application, you may want to set up more features such as remote control, playback events, etc. Configuration and customization options can be found in the react-native-track-player documentation.
-
Testing on Device:
Make sure you test your application on a physical device. Some functionalities may not work on simulators/emulators, especially features related to audio playback.
With these steps, you should be able to play MP3 files from your assets in a React Native application using react-native-track-player.