📜  如何在 ReactJS 中使用音频切换播放/暂停?

📅  最后修改于: 2022-05-13 01:56:46.252000             🧑  作者: Mango

如何在 ReactJS 中使用音频切换播放/暂停?

在本文中,我们将学习使用 ReactJS 为音频文件创建播放/暂停按钮

方法:我们将使用以下步骤:

  • 参考 ReactJS Using Audio Class中的音频文件
  • 将歌曲的默认状态设置为不播放。
  • 制作一个函数来处理歌曲的播放/暂停。
  • 使用音频类的play()pause()函数来执行这些操作。
let song = new Audio(my_song);
song.play();
song.pause();

设置环境和执行:

第 1 步:创建 React App 命令

npx create-react-app foldername

步骤2:创建项目文件夹后,即文件夹名称,使用以下命令移动到它:

cd foldername

第 3 步:创建一个静态文件夹并向其中添加一个音频文件。

项目结构:它将如下所示。

例子:

应用程序.js
import React, { Component } from "react";

// Import your audio file
import song from "./static/a.mp3";

class App extends Component {
  // Create state
  state = {

    // Get audio file in a variable
    audio: new Audio(song),

    // Set initial state of song
    isPlaying: false,
  };

  // Main function to handle both play and pause operations
  playPause = () => {

    // Get state of song
    let isPlaying = this.state.isPlaying;

    if (isPlaying) {
      // Pause the song if it is playing
      this.state.audio.pause();
    } else {

      // Play the song if it is paused
      this.state.audio.play();
    }

    // Change the state of song
    this.setState({ isPlaying: !isPlaying });
  };

  render() {
    return (
      
{/* Show state of song on website */}

{this.state.isPlaying ? "Song is Playing" : "Song is Paused"}

{/* Button to call our main function */}
); } } export default App;