Советы

Как создать музыкальный плеер на React

Как создать музыкальный плеер на React

In this blog post, we will build an Audio player component in React JS. The component will allow users to play, pause, seek through audio, and view the audio’s current time and duration.

As you can see in the above demo video, we have a simple audio player card. It contains a cover image, an input range element to see through the audio, and a play and pause button.

Defining the AudioPlayer component

First, we’ll create our `AudioPlayer` component that takes a single prop `audioSrc`. The `audioSrc` prop is the source of the audio file that we want to play in our player.

function AudioPlayer({ audioSrc }) {
// …
return (
// …
);
}

export default AudioPlayer;

Define state variables for the audio player

const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);

Here, `isPlaying` is a boolean that determines whether the audio is playing. The `currentTime` state variable stores the current time of the audio playback, and `duration` is the total duration of the audio file. We set the initial state of `isPlaying` to `false`, and `currentTime` and duration to 0.

We also create a reference to the audio element using the useRef hook:

const audioRef = useRef(null);

The `audioRef` variable is initialized to `null` and will reference the audio element in the DOM once the component has mounted.

Defining event handlers to play, pause, and toggle the audio

Next, we define some functions that will handle the play, pause, and play/pause toggle events of the audio player:

const handlePlay = () => {
audioRef.current.play();
setIsPlaying(true);
};

const handlePause = () => {
audioRef.current.pause();
setIsPlaying(false);
};

const handlePlayPause = () => {
if (isPlaying) {
handlePause();
} else {
handlePlay();
}
};

These functions are used to control the behavior of the audio player. `handlePlay` plays the audio, `handlePause` pauses the audio, and `handlePlayPause` toggles the audio between playing and paused states.

Defining an event handler to update the time and duration of the audio

We also define a function `handleTimeUpdate` that will be called whenever the `timeupdate` event is triggered on the audio element:

const handleTimeUpdate = () => {
setCurrentTime(audioRef.current.currentTime);
setDuration(audioRef.current.duration);
};

The `handleTimeUpdate` function sets the current time and duration of the audio playback by updating the `currentTime` and `duration` state variables.

Defining an event handler to seek to a specific time in the audio

const handleSeek = (e) => {
audioRef.current.currentTime = e.target.value;
setCurrentTime(e.target.value);
};

The `handleSeek` function is called when the user drags the seek bar to a specific time in the audio file. It updates the `currentTime` variable and seeks to the specified time.

Defining a function to format the duration of the audio

function formatDuration(durationSeconds) {
const minutes = Math.floor(durationSeconds / 60);
const seconds = Math.floor(durationSeconds % 60);
const formattedSeconds = seconds.toString().

padStart(2, «0»);
return `${minutes}:${formattedSeconds}`;
}

The `formatDuration` function takes the duration of the audio in seconds and formats it into minutes and seconds.

It pads the seconds with a zero if it is a single-digit number.

Using the useEffect hook to add and remove an event listener

useEffect(() => {
audioRef.current.addEventListener(«timeupdate», handleTimeUpdate);
return () => {
audioRef.current.removeEventListener(«timeupdate», handleTimeUpdate);
};
}, []);

This useEffect hook adds an event listener to the audio element when the component mounts and removes it when the component unmounts. The event listener listens for changes in the time

JSX code to render audio player

return (

{formatDuration(currentTime)}

{formatDuration(duration)}

{isPlaying ? «pause» : «play_arrow»}

);

The above JSX code renders a player card that contains an image, an HTML audio element, a range input for seeking, and a button for playing or pausing the audio. It also displays the current time and duration of the audio.

Also, check out:

Complete Code of `AudioPlayer` component:

import React, { useState, useRef, useEffect } from «react»;

function AudioPlayer({ audioSrc }) {
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
const audioRef = useRef(null);

const handlePlay = () => {
audioRef.current.play();
setIsPlaying(true);
};

const handlePause = () => {
audioRef.current.pause();
setIsPlaying(false);
};

const handlePlayPause = () => {
if (isPlaying) {
handlePause();
} else {
handlePlay();
}
};

const handleTimeUpdate = () => {
setCurrentTime(audioRef.current.currentTime);
setDuration(audioRef.current.duration);
};

const handleSeek = (e) => {
audioRef.current.currentTime = e.target.value;
setCurrentTime(e.target.value);
};

function formatDuration(durationSeconds) {
const minutes = Math.floor(durationSeconds / 60);
const seconds = Math.floor(durationSeconds % 60);
const formattedSeconds = seconds.toString().padStart(2, «0»);
return `${minutes}:${formattedSeconds}`;
}

useEffect(() => {
audioRef.current.addEventListener(«timeupdate», handleTimeUpdate);
return () => {
audioRef.current.removeEventListener(«timeupdate», handleTimeUpdate);
};
}, []);

return (

{formatDuration(currentTime)}

{formatDuration(duration)}

{isPlaying ? «pause» : «play_arrow»}

);
}

export default AudioPlayer;

Using The `AudioPlayer` component in App.js

import React from «react»;
import AudioPlayer from «./AudioPlayer»;

const AUDIO_FILE = «URL_OF_AUDIO_FILE»;

function App() {
return (

);
}

export default App;

Output:

Как создать музыкальный плеер на React

Conclusion

That’s it, we have created an audio player component in React JS that allows users to play, pause, seek through audio, and view the audio’s current time and duration. Hope it was helpful.

How To Create a Music Player in React Native

Mega Bundle Sale is ON! Get ALL of our React Native codebases at 95% OFF discount ????

In today’s article we will build a React Native Music Player, to showcase how easy it is to build a music app in React Native, that is optimized for both native iOS and Android.

The project we are going to build will look and behave similar to the Spotify player, that all of us are familiar with.

The main goal is to have a basic app with two screens: one with a list of predefined songs and another one with the actual music player.

Как создать музыкальный плеер на React

Music apps are extremely popular nowadays, in the Internet era. Spotify, Apple Music or Youtube Music have had an amazing success among global users. Music is an essential commodity that is used for several reasons ranging from relaxation, therapeutics, partying, self-reflection and so on. 

Without further ado, let’s get started with our React Native music player tutorial.

1. Building Out The UI of The React Native Music Player

As we already mentioned, we are going to use the Spotify design as inspiration for our React Native music player. We are going to assume you are already familiar with functional components, hooks, and styling in React Native, so we are going to cut straight to the chase.

As an overview, the list of songs will consist of a list of objects containing the song title, song URL, music art cover and other vital information as shown in the example JSON below:

{
url: 'https://www.bensound.com/bensound-music/bensound-happyrock.mp3',
title: 'Happy Rock',
artist: 'Benjamin Tissot',
album: «Bensound's rock»,
genre: 'Rock',
date: '2014-05-20T07:00:00+00:00', // RFC 3339
artwork: 'https://www.bensound.com/bensound-img/happyrock.jpg', // Load artwork from the network
duration: 105, // Duration in seconds
}

We hardcoded the list of songs into an array of objects. The list contains music we downloaded from Bensound. For the TrackListScreen we are going to use one external dependency, LinearGradient, to make the UI look more aesthetic by using a gradient. You should install it using the following command:

yarn add react-native-linear-gradient date-fns

On iOS, you also need to install the pods using npx pod-install.

We are also going to create a local object up to hold our music library data /data.js at the root of your project:

// data.js

Читайте также:  Как стать программистом на Java: дорожная карта 2022

export const musiclibrary = [
{
url: 'https://www.bensound.com/bensound-music/bensound-happyrock.mp3',
title: 'Happy Rock',
artist: 'Benjamin Tissot',
album: «Bensound's rock»,
genre: 'Rock',
date: '2014-05-20T07:00:00+00:00', // RFC 3339
artwork: 'https://www.bensound.com/bensound-img/happyrock.jpg', // Load artwork from the network
duration: 105, // Duration in seconds
},
{
url: 'https://www.bensound.com/bensound-music/bensound-anewbeginning.mp3',
title: 'Punky',
artist: 'Benjamin Tissot',
album: «Bensound's rock»,
genre: 'Rock',
date: '2014-05-20T07:00:00+00:00', // RFC 3339
artwork: 'https://www.bensound.com/bensound-img/punky.jpg',
duration: 126, // Duration in seconds
},
{
url: 'https://www.bensound.com/bensound-music/bensound-actionable.mp3',
title: 'Actionable',
artist: 'Benjamin Tissot',
album: «Bensound's rock»,
genre: 'Rock',
date: '2014-05-20T07:00:00+00:00', // RFC 3339
artwork: 'https://www.bensound.com/bensound-img/actionable.jpg',
duration: 122, // Duration in seconds
},
{
url: 'https://www.bensound.com/bensound-music/bensound-romantic.mp3',
title: 'Romantic',
artist: 'Benjamin Tissot',
album: «Bensound's Jazz»,
genre: 'Jazz',
date: '2014-05-20T07:00:00+00:00', // RFC 3339
artwork: 'https://www.bensound.com/bensound-img/romantic.jpg',
duration: 236, // Duration in seconds
},
{
url: 'https://www.bensound.com/bensound-music/bensound-allthat.mp3',
title: 'All That',
artist: 'Benjamin Tissot',
album: «Bensound's Jazz»,
genre: 'Jazz',
date: '2014-05-20T07:00:00+00:00', // RFC 3339
artwork: 'https://www.bensound.com/bensound-img/allthat.jpg',
duration: 146, // Duration in seconds
},
{
url: 'https://www.bensound.com/bensound-music/bensound-love.mp3',
title: 'Love',
artist: 'Benjamin Tissot',
album: «Bensound's Jazz»,
genre: 'Jazz',
date: '2014-05-20T07:00:00+00:00', // RFC 3339
artwork: 'https://www.bensound.com/bensound-img/love.jpg',
duration: 335, // Duration in seconds
},

{
url: 'https://www.bensound.com/bensound-music/bensound-dreams.mp3',
title: 'Dreams',
artist: 'Benjamin Tissot',
album: «Bensound's Electronica»,
genre: 'Electronica',
date: '2014-05-20T07:00:00+00:00', // RFC 3339
artwork: 'https://www.bensound.com/bensound-img/dreams.jpg',
duration: 310, // Duration in seconds
},
{
url: 'https://www.bensound.com/bensound-music/bensound-dance.mp3',
title: 'Love',
artist: 'Benjamin Tissot',
album: «Bensound's Electronica»,
genre: 'Electronica',
date: '2014-05-20T07:00:00+00:00', // RFC 3339
artwork: 'https://www.bensound.com/bensound-img/dance.jpg',
duration: 177, // Duration in seconds
},
];

Next, we set up the UI for the list of tracks src/screens/TrackListScreen.js:

import React, {useEffect, useState} from 'react'; import { View, Text, FlatList, StyleSheet, Pressable, Image, SafeAreaView, TouchableOpacity, } from 'react-native'; import {musiclibrary} from '../../data'; import LinearGradient from 'react-native-linear-gradient'; import TrackPlayerScreen from '../../components/TrackPlayerScreen';import PlayIcon from '../../assets/icons/play.png'; import PauseIcon from '../../assets/icons/pause.png'; export default function TrackListScreen() { const [selectedMusic, setSelectedMusic] = useState(null); const [selectedMusicIndex, setSelectedMusicIndex] = useState(null); const [isPlayerModalVisible, setisPlayerModalVisible] = useState(false); const [isPlaying, setIsPlaying] = useState(false); const [timestamp, setTimestamp] = useState(0); const [mode, setMode] = useState('shuffle') const PlaylistImageView = () => ( SHUFFLE PLAY ); const onSelectTrack = async (selectedTrack, index) => { setSelectedMusic(selectedTrack); setTimestamp(0); setSelectedMusicIndex(index); // remove TrackPlayer.skip(index); // playOrPause(); }; const playOrPause = async () => { setIsPlaying(!isPlaying); }; const onSeekTrack = newTimeStamp => { setTimestamp(newTimeStamp); }; const onPressNext = () => { setTimestamp(0); setSelectedMusic( musiclibrary[(selectedMusicIndex + 1) % musiclibrary.length], ); setSelectedMusicIndex(selectedMusicIndex + 1); }; const onPressPrev = () => { if (selectedMusicIndex === 0) { return; } setTimestamp(0); setSelectedMusic( musiclibrary[(selectedMusicIndex — 1) % musiclibrary.length], ); setSelectedMusicIndex(selectedMusicIndex — 1); }; const renderSingleMusic = ({item, index}) => { return ( {index === 0 && } onSelectTrack(item, index)}> {item.title} {item.artist} ); }; return ( {selectedMusic && ( < TrackPlayerScreen onCloseModal={() => setisPlayerModalVisible(false)} isVisible={isPlayerModalVisible} isPlaying={isPlaying} playOrPause={playOrPause} selectedMusic={selectedMusic} onSeekTrack={onSeekTrack} timestamp={timestamp} onPressNext={onPressNext} onPressPrev={onPressPrev} playbackMode={mode} onClickLoop={()=> mood === «loop» ? setMode(«loop») : setMode(«off»)} /> )} My music item.url} renderItem={renderSingleMusic} /> {selectedMusic && ( setisPlayerModalVisible(true)}> {selectedMusic.title} {selectedMusic.artist} playOrPause()}> )} ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#191414', }, musicTitle: { fontSize: 22, color: '#fff', fontWeight: '500', marginTop: 12, marginHorizontal: 20, marginBottom: 1, }, artisteTitle: { fontSize: 16, color: '#fff', opacity: 0.8, marginHorizontal: 20, marginBottom: 12, marginTop: 1, }, widgetContainer: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 0, height: 60, width: '100%', backgroundColor: '#5E5A5A', }, widgetMusicTitle: { fontSize: 18, color: '#fff', fontWeight: '500', marginTop: 12, marginHorizontal: 10, marginBottom: 1, }, widgetArtisteTitle: { fontSize: 14, color: '#fff', opacity: 0.8, marginHorizontal: 10, marginBottom: 12, marginTop: 1, }, widgetImageStyle: { width: 55, height: 60, marginTop: 3, }, linearGradient: { width: '100%', height: 250, justifyContent: 'center', alignItems: 'center', }, shuffleButton: { color: '#fff', fontSize: 24, fontWeight: 'bold', }, shuffleButtonContainer: { paddingVertical: 15, paddingHorizontal: 35, borderRadius: 40, alignSelf: 'center', backgroundColor: '#1DB954', }, });

Fullstack React: React Daily UI — 009 Creating a music player with React 16

This post is a part of the React Daily UI post series, a joint effort between Jack Oliver, Sophia Shoemaker, and the rest of the team at Fullstack React.
Each day we're explaining in detail how to create a UI component with React.

You can view the Codepen implementation here

Or you view the code on Github here

Welcome to React Daily UI, where every day is opportunity to learn how to build beautiful React applications. We're really excited to be partnering with Jack Oliver who is embarking on this ambitious project with us.

Jack is designing and writing the code for these applications and we're going to deconstruct each one to highlight the features that are unique to React.

Today we're going to learn how to create a music player using some of the new features in React 16.

Overview

In implementing this music player, we are going to learn about some of the changes that are in React 16 — there are quite a few changes, so we won't cover all of them, but we will cover the ones that are important and that you can implement today.

The album art comes from an album by a band called the Glass Animals. Since we can't legally stream the «Glass Animals» soundtrack, we've picked some royalty free music to play in it's place so we can get the full effect of the music player.

Table of Contents

Как создать музыкальный плеер на React

This post is the first of many that will explain step-by-step how to create professional UI components in React. If you want to become a pro at building UIs in React, put in your email below and we'll notify you as each post is completed.

No spam ever & it's easy to unsubscribe.

state in a React application

  • All React applications include a property called state to determine how and what components (and any data associated with those components) should be displayed.
  • Our music player has a state property that contains two important pieces of information, one variable the specifies whether the player is playing music — the playing boolean and one variable that tracks the state of the current track — the currentTrackIndex variable.

this.state = { playing: false, currentTrackIndex: 0
};

What is state?

When we refer to a component's state, we mean a snapshot of the instance of the component on the page.

React's components can define their own state which we'll use in today's post. When we use state in a React component the component is said to be stateful. A React component can define it's own state using a state property for handling stateful components, such as our music player.

As the user clicks the play, pause, next,previous buttons and the tracks in the player, our component will update it's current state.

props vs state

For React applications it's important to understand the distinction between props and state. Our music player has two state variables that determine the way our application is displayed at a given point in time.

The App component is our main component that drives the display of our child components, the Controls component and the TrackList component.

In order for these two components to receive information about the state of our application, the App component will pass information down as props to the children components. These props can then be used in the child component to display their pieces of the application correctly.

Another important thing to understand is that every time our App component updates, our Controls component and TrackList component will be updated as well because they rely on information from the App component.

Читайте также:  Особенности использования WebView в Android-приложениях

Controls

Our Controls component is the first child of our App component. The Controls component is given two props: onClick and playing.

The onClick prop allows us to pass down our handleClick function we've defined in the App component to the Controls component. When the user clicks one of the buttons in our Controls component, the handleClick function will get called.

The playing prop allow the Controls component to know what the current state of the player is so we can properly render the play icon or the pause icon.

Let's explore how we render our buttons and handle clicks in our Controls component.

In our Controls component we have three important buttons:

  1. The (next) button — an arrow icon pointing to the right — which selects the next track in the list

When each of these buttons are clicked, we call the click handler function that we passed in from the App component. Each of the buttons in our music player application has an id which will aid us in determing how a particular click should be handled.

In the internals of the handleClick function, we use a switch statement that uses the id of the button that was clicked — e.target.id to determine how to handle the action from the button. Let's take a look at what happens in each case of the switch statement:

The play button

When the play button is clicked, we will need to update a few parts of our application. One part of our application we need to update is to switch the play icon to the pause icon.

The other aspect of our application we need to update is the currentTrackIndex if it is currently set to 0.

In order to change these two parts of our application we will call setState, a function available to every React component.

Frontender`s Spectre

Данная статья является переводом. Ссылка на оригинал.

В этой статье мы напишем музыкальный плеер, который будет выглядеть так:

Это и все последующие изображения взяты отсюда.

Подготовка и настройка среды

Я предполагаю, что у вас есть знания о следующих технологиях:

Настройка среды проста: у вас должен быть предварительно установлен node.js для запуска команды в терминале.

https://www.youtube.com/watch?v=i_tZBYQjVRs\u0026list=PL3kZLkdYfiOR0uC9SPzXlxozwE3Lewhu0

Перейдите в каталог, в котором вы хотите создать проект. Теперь запустите терминал и введите приведенную ниже команду, чтобы установить react-проект.

npx create-react-app react-music-player

Удалите шаблон полностью и ненужный код. Теперь мы можем продолжить.

Зависимости

Нам нужно установить следующие библиотеки в наш проект:

  • use-sound будет обрабатывать аудиофайл. Он будет загружать, воспроизводить и приостанавливать звук вместе с другими функциями.

Установите его с помощью следующей команды:

npm i use-sound

  • react-icons добавит значки воспроизведения, паузы, следующей и предыдущей композиции в плеер.

Установите его с помощью следующей команды:

npm i react-icons

Player.js

Создайте каталог component в папке src. Внутри создайте компонент с именем Player.js. Этот компонент будет нашим музыкальным проигрывателем.

Импорт

Библиотеки, которые нужно импортировать в файл:

import { useEffect, useState } from «react»;
import useSound from «use-sound»; //для работы со звуком
import qala from «../assets/qala.mp3»; // импорт музыки
import { AiFillPlayCircle, AiFillPauseCircle } from «react-icons/ai»; // иконки для воспроизведения и паузы
import { BiSkipNext, BiSkipPrevious } from «react-icons/bi»; // иконки для следующего и предыдущего трека
import { IconContext } from «react-icons»; // для кастомизации иконок

Воспроизведение и приостановка звука

Давайте реализуем обязательную функцию проигрывателя, которая отвечает за воспроизведение и приостановку звука.

Вверху у нас есть состояние isPlaying для хранения текущего статуса проигрывателя. Это будет полезно при условном рендеринге значка воспроизведения/паузы в соответствии со статусом проигрывателя.

const [isPlaying, setIsPlaying] = useState(false);

Нам нужно инициализировать файл useSound со звуком. Он вернет воспроизведение, паузу, продолжительность и метод звука.

const [play, { pause, duration, sound }] = useSound(qala);

play и pause для воспроизведения и приостановки звука. duration для длины дорожки в миллисекундах. sound предоставит нам метод howler.js для звука.

Создайте функцию для обработки кнопок воспроизведения и паузы. Вот код для него.

const playingButton = () => {
if (isPlaying) {
pause(); // приостанавливаем воспроизведение звука
setIsPlaying(false);
} else {
play(); // воспроизводим аудиозапись
setIsPlaying(true);
}
};

Теперь пришло время добавить компонент пользовательского интерфейса плеера в return. Вот код для него.

return (

Playing Now

Rubaiyyan

Qala

{!isPlaying ? (

) : (

)}

);

Для обложки я использовал Loren Picsum для генерации случайного изображения.

Вы можете посмотреть здесь CSS-файл:

body {
background-color: #e5e5e5;
}

.App {
font-family: sans-serif;
text-align: center;
}

.component {
background-color: white;
width: 25%;
max-width: 600px;
margin: 1em auto;
padding-bottom: 2em;
border: 0.1px solid black;
border-radius: 10px;
}

.musicCover {
border-radius: 10%;
}

.playButton {
background: none;
border: none;
align-items: center;
justify-content: center;
}

.subTitle {
margin-top: -1em;
color: #4f4f4f;
}

.time {
margin: 0 auto;
width: 80%;
display: flex;
justify-content: space-between;
color: #828282;
font-size: smaller;
}

.timeline {
width: 80%;
background-color: #27ae60;
}

input[type=»range»] {
background-color: #27ae60;
}

@media (max-width: 900px) {
.component {
width: 50%;
}
}

Запустите сервер react. Если все хорошо, вы сможете увидеть экран ниже.

Нажмите на кнопку воспроизведения, чтобы воспроизвести аудио.

Добавление временной шкалы аудио с текущим временем и продолжительностью аудио

Теперь давайте добавим временную шкалу в плеер. Временная шкала будет контролироваться пользователем. Любые изменения в нем изменят текущую позицию аудио.

Давайте посмотрим на состояние, которое мы используем. Ниже приведены комментарии для объяснения каждого состояния.

const [currTime, setCurrTime] = useState({
min: «»,
sec: «»,
}); // текущее положение звука в минутах и секундах

const [seconds, setSeconds] = useState(); // текущая позиция звука в секундах

Мы получаем свойства длительности из файла useSound. Поскольку продолжительность указывается в миллисекундах, мы преобразовали ее в минуты и секунды.

useEffect(() => {
const sec = duration / 1000;
const min = Math.floor(sec / 60);
const secRemain = Math.floor(sec % 60);
const time = {
min: min,
sec: secRemain
};

Теперь для текущей позиции аудио у нас есть метод sound.seek([]). Мы запускаем эту функцию каждую секунду, чтобы изменить текущую позицию проигрывания звука. Затем получаем значение позиции проигрывания в секундах. Переводим в минуты и секунды. После преобразования мы устанавливаем состояние с текущим значением. Вот код для него.

useEffect(() => {
const interval = setInterval(() => {
if (sound) {
setSeconds(sound.seek([])); // устанавливаем состояние с текущим значением в секундах
const min = Math.floor(sound.seek([]) / 60);
const sec = Math.floor(sound.seek([]) % 60);
setCurrTime({
min,
sec,
});
}
}, 1000);
return () => clearInterval(interval);
}, [sound]);

Теперь о возвращаемом значении. Вот код.

{currTime.min}:{currTime.sec}

{time.min}:{time.sec}

{
sound.seek([e.target.value]);
}}
/>

Значение входного сигнала диапазона является second-состоянием, которое сообщает позицию проигрывания аудио. При изменении диапазона пользователем, мы вызываем метод soud.seek(), чтобы изменить текущую позицию аудио.

Вывод

После успешного завершения проекта вы сможете увидеть:

Вы можете посмотреть полный проект с кодом и выводом по ссылке.

Дополнительные возможности

Вы можете работать над музыкальным проигрывателем, чтобы добавить дополнительные функции, например:

  • Приложение загружает много песен, однако в настоящее время воспроизводит только одну песню. Используйте кнопки перемотки трека для смены трека.
  • Изменение названия и альбома аудио в соответствии с проигрываемой песней.
  • Добавьте больше функций, которые, по вашему мнению, должен иметь музыкальный проигрыватель.

Заключение

Мы создали собственный музыкальный плеер. Этот проект поможет вам в обработке аудиофайлов в React. Мы добавили функции воспроизведения и паузы. Также добавлена ​​временная шкала аудио. Пользователи могут изменить текущую позицию аудио на временной шкале. Не стесняйтесь добавлять дополнительные функции в проект. Я надеюсь, что этот проект помог вам понять метод обработки музыки в React.

Читайте также:  ТОП-12 сочетаний клавиш VS Code для продуктивной работы

Интересно, перейти к каналу

Implement Audio Player in React

React applications are not exclusively for displaying visual content. Sometimes audio content is essential as well.

We can configure the React component to play music and have a button to pause and resume play when needed.

Create a Class Component to Implement Audio Player in React

In React, you can create a component using the ES6 class component syntax to play any music files. For that, we will utilize multiple features: state, the native Audio() constructor, lifecycle hooks, and so on.

Let’s look at the actual example of how to create a React class component that plays audio.

class PlayMusic extends React.Component {
state = {
songplaying: false
};
song = new Audio(
«https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3»
);
componentDidMount() {
this.song.addEventListener(«ended», () =>
this.setState({ songplaying: false })
);
}

componentWillUnmount() {
this.song.removeEventListener(«ended», () =>
this.setState({ songplaying: false })
);
}

switchPlay = () => {
this.setState({ songplaying: !this.state.songplaying }, () => {
this.state.songplaying ? this.song.play() : this.song.pause();
});
};

render() {
return (

{this.state.songplaying ? «Pause» : «Play»}

);
}
}

Here, we have a PlayMusic component, where we initiate the state with one property called songplaying. When the users visit this website, we don’t want the audio to be playing, so by default, the songplaying state property will be false.

Then, we create an instance of the Audio() constructor and store it in the variable called song. This constructor takes one argument, the URL, to the audio file.

Then, we use the lifecycle methods, componentDidMount() and componentWillUnmount(), to set and remove event listeners for the ended event on the song variable, which is an instance of the Audio() constructor. We also set the function to handle the ended event.

We call the setState() method to change the value of the songplaying state property. Once the audio file has ended, the state variable should be set to false.

Finally, we return the container with one button. Clicking on this button will trigger an onClick event, which will execute the switchPlay function.

The this.setState() method will set the value of the songplaying property to the opposite of its current value. If the state property is currently false, it will be set to true, and vice versa.

In addition, if the state value is true, the event handler will call the .play() method on the instance of the Audio() constructor. If the audio is false, it will instead call the .pause() method.

Finally, we conditionally display the button text. We show the Pause text if the song is currently playing; if it’s not, we indicate Play instead.

Check out the live demo of the example on this CodeSandbox.

Create a Functional Component to Implement Audio Player in React

Since React version 16.8, functional components in React have many of the same features as Class components. This is thanks to the introduction of hooks, such as useState(), useHook(), and other custom hooks.

Let’s implement a music player in a functional component. First, we define a custom useAudio hook, then call it in the MusicPlayer component.

import React, { useState, useEffect } from «react»;

const useAudio = url => {
const [song] = useState(new Audio(«https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3»));
const [play, setPlay] = useState(false);

const toggle = () => setPlay(!play);

useEffect(() => {
play ? song.play() : song.pause();
},
[play]
);

useEffect(() => {
song.addEventListener('ended', () => setPlay(false));
return () => {
song.removeEventListener('ended', () => setPlay(false));
};
}, []);

return [play, toggle];
};

const MusicPlayer = () => {
const [playMusic, setMusic] = useAudio(«https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3»);

return (

{playMusic ? «Pause» : «Play»}

);
};

export default Player;

This works primarily according to the same principle as the previous example. The main difference is that instead of using lifecycle methods, we use the useEffect() hook to add and remove event listeners for the audio.

We also use the useState() hook to define state variables, such as song and play. The former stores a reference to the Audio() constructor, and the latter stores the status of the music.

The toggle function also switches the current value of the play state variable, allowing us to stop playing music and continue when needed.

This custom hook allows you to set the audio easily. Provide the link to the song file, and then use the ternary operator to check the value of the state variable and display the button text accordingly.

Create an Audio Player with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create an audio player with React and JavaScript.

We can create the React project with Create React App.

To install it, we run:

npx create-react-app audio-player

with NPM to create our React project.

Create the Audio Player

To create the audio player, we write:

import React, { useRef, useState } from «react»;

export default function App() {
const audioPlayer = useRef();
const [currentTime, setCurrentTime] = useState(0);
const [seekValue, setSeekValue] = useState(0);

const play = () => {
audioPlayer.current.play();
};

const pause = () => {
audioPlayer.current.pause();
};

const stop = () => {
audioPlayer.current.pause();
audioPlayer.current.currentTime = 0;
};

const setSpeed = (speed) => {
audioPlayer.current.playbackRate = speed;
};

const onPlaying = () => {
setCurrentTime(audioPlayer.current.currentTime);
setSeekValue(
(audioPlayer.current.currentTime / audioPlayer.current.duration) * 100
);
};

return (

Your browser does not support the
audio element.

{currentTime}

{
const seekto = audioPlayer.current.duration * (+e.target.value / 100);
audioPlayer.current.currentTime = seekto;
setSeekValue(e.target.value);
}}
/>

play
pause
stop
setSpeed(0.5)}>0.5x
setSpeed(1)}>1x
setSpeed(1.5)}>1.5x
setSpeed(2)}>2x

);
}

We create the audioPlayer ref that we assign to the audio element.

Then we create the currentTime state to set the current time of the audio playback.

  • seekValue has the time value we seek to.
  • The play function gets the audioPlayer and call play on it to play the video.
  • The pause function calls pause on the audio element.
  • The stop function calls pause and also set the currentTime of the audio element to 0 to reset the play position back to the beginning.
  • The onPlaying function sets the currentTime to the audio element’s currentTime value in seconds.
  1. setSeekValue sets the seekValue to a value between 0and 100.
  2. Below that, we have the audio element that has the onTimeUpdate prop set to the onPlaying function to set the currentTime .
  3. Then we show the currentTime to the user.
  4. The range input lets us change its value by moving the slider dot.
  5. value is set to seekValue which we can change and we change that with the onChange callback and the onPlaying function.
  6. In the onChange prop, we also set the currentTime of the audio player element.

Below that, we have the play, pause, and stop buttons to call the respective functions when we click them.

And we have 3 buttons that call setSpeed when we click them.

Conclusion

We can create an audio player easily with React and JavaScript.

Related Posts

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *