Open In App

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

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.




//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 GeeksforGeeks
            </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.

npx react-native run-android
npx react-native run-ios

Output:


Article Tags :