音频文件无法在reactjs中播放

时间:2019-09-27 12:12:02

标签: javascript html reactjs audio-player

我一直试图在Recact.js中播放音频文件,但无法播放。 我没有遇到任何错误,滚动条显示出来,但是播放按钮不起作用。我试过播放歌曲以检查文件是否损坏。 mp3文件可以正常工作。

import React from 'react'

class AudioPlayer extends React.Component {
  render() {
    return (
      <div>
        <audio ref="audio_tag" src="./abc.mp3" controls autoPlay/>
      </div>
    );
  }
}

export default AudioPlayer;

3 个答案:

答案 0 :(得分:0)

由于您使用的是create-react-app,因此建议您将mp3文件移动到公用文件夹中,然后尝试以下操作,并使用我称为pathToPublic的内容查找所需的任何路径:

import abc from '.../pathToPublic/public/abc.mp3'

<audio
  ref="audio_tag"
  autoPlay={true}
  controls={true} >
  <source type="audio/mp3" src={abc} />
</audio>

让我们知道它是否有效。

答案 1 :(得分:0)

可以放置正确的src文件吗?或者如果要检查的话就放在外部

  <div>
    <audio ref="audio_tag" src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3" controls autoPlay/>
  </div> 

<audio
  ref="audio_tag"
  autoPlay={true}
  controls={true}>
  <source type="audio/mp3" src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3" />
</audio>

答案 2 :(得分:0)

./是相对路径,因此您的音频文件需要与分发包位于同一文件夹中。

如果您想使音频文件和播放器保持解耦状态,可以这样做,但是要确保它能正常工作,请确保a)将文件复制到应用程序的输出文件夹中; b)从根目录引用路径,像这样:

class AudioPlayer extends React.Component {
  render() {
    return (
      <div>
        <audio ref="audio_tag" src="/assets/sounds/abc.mp3" controls autoPlay/>
      </div>
    );
  }
}

您也可以导入音频文件并直接使用:

import abc from './../path/to/file/abc.mp3';

class AudioPlayer extends React.Component {
  render() {
    return (
      <div>
        <audio ref="audio_tag" src={abc} controls autoPlay/>
      </div>
    );
  }
}

这是一个工作沙盒,演示了导入方法:https://codesandbox.io/s/strange-leakey-7lk6f