Create a Music Player using React-Native

React Native is a powerful framework that allows you to build mobile applications using JavaScript and React. In this tutorial, we are going to build a Music Player using React-Native. Here we will load the music files stored in our device and then use the play and pause button to control the music. We can also see the progress of the music played in duration.

Preview of final output: Let us have a look at how the final output will look like.

Prerequisites & Technolgies Used:

Approach to create Music Player App

  • In this app, we will have a single page or screen.
  • At the start of app, using useEffect hook, we will call a function to load the music files.
  • Then we will save the device music file URIs and File names in a array.
  • In the component, array will be mapped and displayed in a column with file names.
  • On the left of each tile, there will be play/pause button. On clicking it, the file will be loaded.
  • After loading, another useEffect will fire on change of sound variable. It will store the progress of duration of music played. We will display the progress.
  • After completion of music, sound will be unloaded.

Steps to Create React Native Application:

Step 1: Create the project:

npx create-expo-app music-player-app

Step 2: Navigate to the project

cd music-player-app

Step 3: Install the packages as follows:

npx expo install expo-av
npx expo install @expo/vector-icons
npx expo install expo-media-library

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"expo": "~49.0.15",
"expo-status-bar": "~1.6.0",
"react": "18.2.0",
"react-native": "0.72.6",
"expo-media-library": "~15.4.1",
"expo-av": "~13.4.1",
"@expo/vector-icons": "^13.0.0"
},

Example: In this example we are following the above-explained approach.

Javascript




//App.js
 
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import * as MediaLibrary from 'expo-media-library';
import { useEffect, useState } from 'react';
import { Audio } from 'expo-av';
import Ionicons from '@expo/vector-icons/Ionicons';
 
export default function App() {
    const [musicFiles, setMusicFiles] = useState([])
    const [playing, setPlaying] = useState(-1)
    const [sound, setSound] = useState(null);
    const [progressDuration, setProgressDuration] = useState(0)
    const fetchMusicFiles = async () => {
        const permission = await MediaLibrary.requestPermissionsAsync(
 
        );
        const media = await MediaLibrary.getAssetsAsync({
            mediaType: MediaLibrary.MediaType.audio,
        });
        setMusicFiles(media.assets)
    }
    const playMusic = async (fileUri) => {
        const { sound } = await Audio.Sound.createAsync({
            uri: fileUri,
        });
        setSound(sound);
        await sound.playAsync();
    }
 
    const pauseMusic = async () => {
        await sound.pauseAsync();
    }
    useEffect(() => {
        if (!sound) {
            return;
        }
        sound.setOnPlaybackStatusUpdate(
            async (status) => {
                if (status.didJustFinish) {
                    setPlaying(-1)
                    await sound.unloadAsync();
                    console.log("finished")
                    setSound(null);
                }
                else {
                    setProgressDuration(status.positionMillis / 1000)
                }
            }
        );
    }, [sound])
    useEffect(() => {
        fetchMusicFiles()
    }
        , [])
    return (
        <View style={styles.container}>
            <StatusBar style="auto" />
            <Text style={styles.heading}>
                Welcome to w3wiki
            </Text>
            <View style={styles.list}>
 
                {musicFiles.map((file, index) => {
 
                    return (
                        <View key={index}>
 
                            <TouchableOpacity onPress={
                                playing !== index ?
                                    () => {
                                        playMusic(file.uri)
                                        setPlaying(index)
                                    } :
                                    () => {
                                        pauseMusic()
                                        setPlaying(-1)
                                    }
                            } style={styles.playButton}>
                                <View style={{
                                    flexDirection: "row",
                                    justifyContent: "space-between",
                                    alignItems: "center",
                                }}>
                                    <Ionicons
                                        name={playing !== index ?
                                            "play" :
                                            "pause"}
                                        size={30}
                                        color="white" >
                                        <Text
                                            style={styles.fileName}>
                                            {file.filename}
                                        </Text>
 
 
                                    </Ionicons>
                                </View>
                                {/* progress duration if index == currentIndex*/}
                                <View style={styles.row}>
 
                                    {playing === index ?
                                        <Text style={styles.fileName}>
                                            {progressDuration} / {file.duration}
                                        </Text> :
                                        <></>
                                    }
                                </View>
                            </TouchableOpacity>
                        </View>
                    )
                })}
            </View>
        </View>
    );
}
 
 
const styles = StyleSheet.create({
    row: {
        flexDirection: "row",
        justifyContent: "space-evenly",
    },
    container: {
        backgroundColor: "#fff",
        height: "100%",
        marginTop: 50,
    },
    heading: {
        color: "green",
        fontSize: 30,
        textAlign: "center",
        fontWeight: "bold",
    },
    list: {
        marginTop: 20,
        flex: 1,
        flexDirection: "column",
    },
    fileName: {
        fontSize: 18,
        color: "white",
        fontWeight: 'bold',
    },
    playButton: {
        backgroundColor: 'gray',
        borderRadius: 50,
        padding: 10,
        margin: 10,
    },
});


Step to run the application:

Step 1: Navigate to the terminal or command prompt and type the required command there to run the React native application.

npx expo start

Step 2: Depending on your Operating System, type the following command.

  • To run on Android:
npx react-native run-android
  • To run on IOS:
npx react-native run-ios

Output:



Contact Us