【问题标题】:React JS audio does not playReact JS音频不播放
【发布时间】:2020-10-20 15:31:08
【问题描述】:

我有一个名为“app.js”的反应文件,代码如下:

import React from 'react';


const App = () => {
   
   const play = (url) => {
       new Audio(url).play();
   }

   return <>
       <input type="button" value="play" onClick={()=> play("./au.mp3")} />
       <audio src="./au.mp3" id="audio"></audio>
   </>;
}

export default App;

一切设置正确,如果按钮确实呈现。但是,当我按下它时,音频(与其他文件位于同一“src”目录中)无法播放。

这是错误:

Uncaught Error: The error you provided does not contain a stack trace.
   at S (index.js:1)
   at V (index.js:1)
   at index.js:1
   at index.js:1
   at a (index.js:1)
localhost/:1 Uncaught (in promise) DOMException: Failed to load because no supported source was found.

关于为什么这可能不起作用的任何想法?

【问题讨论】:

    标签: javascript reactjs button audio playback


    【解决方案1】:

    所以,您的示例实际上对我有用,所以您的音频文件可能有问题?请参阅here,除了音频 url,我没有更改您的代码中的任何内容(我使用的是来自 Mozilla 的 MDN 条目on Audio object 的公开可用文件)

    如果你想在 React Component 中控制音频,你需要使用一个叫做“ref”的东西(供参考)。

    Refs 提供了一种访问 DOM 节点或在 render 方法中创建的 React 元素的方法。

    您目前正在做的是在您的play 方法中创建一个不同的音频对象。

    因此,您可以使用 React 中的 ref 属性和 useRef 实用程序来获取 DOM 元素的句柄,并像这样控制您的音频:

    const App = () => {
      const audioRef = useRef(null);
      const play = (url) => {
        audioRef.current.play();
      };
    
      return (
        <>
          <input type="button" value="play" onClick={() => play()} />
          <audio
            src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"
            ref={audioRef}
          ></audio>
        </>
      );
    };
    

    See the second example working here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多