首页 > 解决方案 > 如何将 mp3 文件添加到反应 js 文件中

问题描述

我正在尝试为我的 react js 应用程序播放单个 mp3 文件。但是,当我向我的方法添加文件路径时,它无法识别它。mp3 位于应用程序内。

我将路径放在变量中,然后将变量放入 html 音频元素中。

如何让我的 mp3 在我的文件中播放?

import React, { useState,useEffect } from "react";


const moby = require('../music/mobyPorcelain.mp3')
const Sound = new Audio(moby)


export default function Header()  {
  
  const [playInLoop, setPlayInLoop] = useState(false);

  useEffect(()=> {
    Sound.load();
  }, [])

  useEffect(() => {
    Sound.loop = playInLoop
  },[playInLoop])

  const playSound = () => {
    Sound.play();
  }

  const pauseSound = () => {
    Sound.pause();
  }

const stopSound = () => {
  Sound.pause();
  Sound.currentTime = 0;
}
 

  
    return (
                  <div>
                    <h3>Moby porcelain</h3>
                    <input
                    type='button'
                    className='btn btn-primary mr-2'
                    value='play'
                    onclick={playSound}/>
                    <input
                    type='button'
                    className='btn btn-warning mr-2'
                    value='pause'
                    onclick={pauseSound}/>
                    <input
                    type='button'
                    className='btn btn-danger mr-3'
                    value='stop'
                    onclick={stopSound}/>
                    <label><input type='checkbox' checked={playInLoop} onChange={e => setPlayInLoop(e.target.checked)}/></label>
                  </div>
                  
    );
  
}

标签: reactjsmp3

解决方案


这是我尝试调试代码时控制台的样子:

在此处输入图像描述

重构onclickonClick它应该可以工作

编辑 rough-worker-3znu5


推荐阅读