javascript - HTML5 音频未在本地主机的 React 应用程序中播放

标签 javascript reactjs cmd localhost html5-audio

我正在使用 React.js 和 HTML5 网络音频 javascript API 制作一个 mp3 播放器。我刚刚学习 React 两周,所以我只是习惯了结构和设置(使用组件等),但是我有几年的 JavaScript 经验。

我在浏览器中使用 React 时让 mp3 播放器正常工作。 IE。我有一个 index.html 文件,我包含了 React 脚本,如下所示:

<script src="js/react.min.js"></script>
<script src="js/react-dom.min.js"></script>
<script src="js/browser.min.js"></script>

现在我想习惯使用命令行和本地主机构建 React 应用程序,因此我开始重写代码以在该环境中使用。 我首先按如下方式创建骨架应用程序:

create-react-app my-app
cd my-app/
npm start

然后我添加了我自己的组件等。 该应用程序在 localhost:3000 上正确显示,但音频文件似乎无法在此环境中播放。我不确定问题是否与 HTML5 音频直接相关,只是在 localhost 中不起作用,或者是其他原因。 没有返回任何错误。

我已经简化了我的代码,并且还在 mp3 文件的目录中硬编码到音频标签(请参阅 AudioPlayer 组件),以便查看我是否可以让音频元素工作。

你能看到我可能遗漏的任何东西吗?谢谢

应用组件

    import React, { Component } from 'react';
    import Header from './Header';

    import AudioPlayer from './AudioPlayer';

    import Controls from './Controls';

    import './music-player.css';
    import './css/font-awesome.css';


    class App extends Component {

         //This class is the main component of the application.
         //it contains the header, the audio player and the side panel components.
         constructor(props) {
                super(props);
                this.state = {
                sidePanelIsOpen: false,
                currentSoundIndex: 0,
                isPlaying: false,
                playerDuration: 0,
                currentTime: "0:00",
                currentWidthOfTimerBar: 0,
                backButtonIsDisabled: false,
                forwardButtonIsDisabled: false,
                playButtonIsDisabled: false


            };
            this.toggleSidePanel = this.toggleSidePanel.bind(this);

        }   
        componentDidMount() {
            this.player = document.getElementById('audio_player');
            this.player.load();
            this.player.play(); //this is not doing anything
        }   
        toggleSidePanel(){
            var sidePanelIsOpen = this.state.sidePanelIsOpen;
            this.setState({sidePanelIsOpen: !sidePanelIsOpen})
        }


        render() {


            return(<div>
                <div id="main-container" className={this.state.sidePanelIsOpen === true ? 'swipe-left' : ''}>
                <div className="overlay">

                <AudioPlayer sounds={this.props.sounds} currentSoundIndex={this.state.currentSoundIndex} />
                </div>  
                </div>


                <div id="side-panel-area" className="scrollable">       
                    <div className="side-panel-container">
                    <div className="side-panel-header"><p>Menu</p></div>

                    </div>
                </div>
                </div>
            );  
        }

    }

    export default App;

音频播放器组件

    import React, { Component } from 'react';
    import './music-player.css';

    const AudioPlayer = function(props) {
        var mp3Src = props.sounds[props.currentSoundIndex].mp3;
        console.log(mp3Src); //this is returning the correct mp3 value
            return (<audio id="audio_player">
            <source id="src_mp3" type="audio/mp3" src="sounds/0010_beat_egyptian.mp3" />
            <source id="src_ogg" type="audio/ogg" src=""/>
            <object id="audio_object" type="audio/x-mpeg" width="200px" height="45px" data={mp3Src}>
                <param id="param_src" name="src" value={mp3Src} />
                <param id="param_src" name="src" value={mp3Src} />
                <param name="autoplay" value="false" />
                <param name="autostart" value="false" />
            </object>
            </audio>    
            );

    }

    export default AudioPlayer;

索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './music-player.css';

var sounds = [{"title" : "Egyptian Beat", "artist" : "Sarah Monks", "length": 16, "mp3" : "sounds/0010_beat_egyptian.mp3"}, 
        {"title" : "Euphoric Beat", "artist" : "Sarah Monks", "length": 31, "mp3" : "sounds/0011_beat_euphoric.mp3"},
        {"title" : "Latin Beat", "artist" : "Sarah Monks", "length": 59, "mp3" : "sounds/0014_beat_latin.mp3"}, 
        {"title" : "Pop Beat", "artist" : "Sarah Monks", "length": 24, "mp3" : "sounds/0015_beat_pop.mp3"},
        {"title" : "Falling Cute", "artist" : "Sarah Monks", "length": 3, "mp3" : "sounds/0027_falling_cute.mp3"}, 
        {"title" : "Feather", "artist" : "Sarah Monks", "length": 6, "mp3" : "sounds/0028_feather.mp3"},
        {"title" : "Lose Cute", "artist" : "Sarah Monks", "length": 3, "mp3" : "sounds/0036_lose_cute.mp3"}, 
        {"title" : "Pium", "artist" : "Sarah Monks", "length": 3, "mp3" : "sounds/0039_pium.mp3"}];

ReactDOM.render(<App sounds={sounds} />, document.getElementById('root'));

registerServiceWorker();

最佳答案

经过一些试验,我发现需要导入 mp3 文件(使用 import)才能在此环境中播放它。

所以我找到了一个解决方案并按如下方式编辑了我的 AudioPlayer 组件(效果很好):

import React, { Component } from 'react';
import './music-player.css';
//Now we import the mp3 file that this JavaScript file uses.
//This will ensure that when the project is built, 
//webpack will correctly move the mp3 file into the build folder, 
//and provide us with the right paths.  
//See docs: https://create-react-app.dev/docs/adding-images-fonts-and-files/
import mp3_file from './sounds/0010_beat_egyptian.mp3'; 

const AudioPlayer = function(props) {
    
        return (<audio id="audio_player">
        <source id="src_mp3" type="audio/mp3" src={mp3_file}/>
        <source id="src_ogg" type="audio/ogg" src=""/>
        <object id="audio_object" type="audio/x-mpeg" width="200px" height="45px" data={mp3_file}>
            <param id="param_src" name="src" value={mp3_file} />
            <param id="param_src" name="src" value={mp3_file} />
            <param name="autoplay" value="false" />
            <param name="autostart" value="false" />
        </object>
        </audio>    
        );
  
}
export default AudioPlayer;

2022 年更新

在某些情况下,最好将您的文件(图像、mp3 文件等)存储在公用文件夹中。 此类情况包括您是否需要将这些文件动态加载到您的应用中。 (参见文档 https://create-react-app.dev/docs/using-the-public-folder/)

由于(在我的项目中)我有多个想要动态加载的 mp3 文件,我发现将我的 mp3 文件存储在公共(public)文件夹中更适合我的应用程序。

注意:将文件存储在公共(public)文件夹中时,您不需要“导入”它们,但必须使用公共(public)环境变量 (process.env.PUBLIC_URL) 以便正确的路径(到您的 public 文件夹)将被引用。

这是我的新解决方案:

  1. 我在 public 文件夹中创建了一个名为 sounds 的文件夹。
  2. 然后我将我的音频组件(在原始帖子中)更改为 以下内容:

.

import React from 'react';
    const AudioPlayer = props => {
      
      let mp3_file = process.env.PUBLIC_URL + props.sounds[props.currentSoundIndex].mp3;
      return (<audio id="audio_player">
        <source id="src_mp3" type="audio/mp3" src={mp3_file} />
        <source id="src_ogg" type="audio/ogg" src={mp3_file} />
        Your browser does not support this audio player.
      </audio>  
      );
    }
    
    export default AudioPlayer;

注意:如果您决定将文件存储在 public 文件夹中,那么它们将不会成为 webpack 构建的一部分,因此如果文件丢失,我们在编译期间不会出现错误,因此我们不会知道它丢失了。 (用户将获得 404)。

如果您选择将文件存储在 src 文件夹中,那么您需要使用 import 以便 webpack 知道将文件包含在构建中。这样做的好处是,如果任何文件不存在,您将在编译期间遇到错误。

关于javascript - HTML5 音频未在本地主机的 React 应用程序中播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44121471/

相关文章:

javascript - 将数字字段与隐藏的 div 关联

javascript - document.createElement();有我可以创建的元素列表吗?

image - 将 native 上传图像 react 为文件

windows - "rm -rf"相当于 Windows?

JAVA新手警报: Trying to run Java class and getting ClassNotFoundException

python - 在 Windows 上从 cmd 使用 virtualenv 时出现 importError

javascript - 在 javascript 中禁用 anchor 标记并删除下划线

javascript - 通过检查句子的第一个字母在网页上显示数据库中的数据

javascript - 防止 React 重新渲染特定的子组件

javascript - 使用 webpack 时出现错误 : Cannot 'file' or 'directory' ./lib/React