首页 > 解决方案 > React JS,HTML音频标签未加载音乐文件

问题描述

使用 create-react-app 我创建了应用程序,浏览器audio标签未加载 mp3 文件。


import React from 'react';
import './App.css';

function App() {
  return (
    <div className="App">

  <audio controls src="Kalimba.mp3">
        Your browser does not support the
        <code>audio</code> element.
      </audio>

    </div>
  );
}

export default App;

文件结构作为图像附加。在此处输入图像描述

标签: javascriptreactjs

解决方案


不确定是否mp3会开箱即用,但根据文档的一个选项 可能是

import React from 'react';
import file from './foobar.mp3'; // Tell webpack this JS script uses this file
console.log(file); // /foobar.84287d09.mp3
function Foobar() {
  // Import result is the URL of your file
  return (<audio controls src={file}>
    Your browser does not support the
    <code>audio</code> element.
  </audio>);
}
export default Foobar;

另一种方法是将文件放入mp3文件public,然后:

render() {
  // Note: this is an escape hatch and should be used sparingly!
  // Normally we recommend using `import` for getting asset URLs
  return (<audio controls src={process.env.PUBLIC_URL + '/foobar.mp3'}>
    Your browser does not support the
    <code>audio</code> element.
  </audio>);
}

推荐阅读