我有这个名为“app.js”的 react 文件,代码如下:
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.
关于为什么这可能不起作用的任何想法?
最佳答案
所以,你的例子实际上对我有用,所以你的音频文件可能有问题?见 here ,除了音频 url,我没有更改您的代码中的任何内容(我使用的是来自 Mozilla 的 MDN 条目 on Audio object 的公开可用文件)
如果你想在 React Component 中控制音频,你需要使用一个叫做“ref”的东西(供引用)。
Refs provide a way to access DOM nodes or React elements created in the render method.
您当前正在做的是在您的
play
中创建一个新的、不同的音频对象。方法。因此,您可以使用
ref
来获取 DOM 元素的句柄。属性和 useRef
来自 React 的实用程序并像这样控制您的音频: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
关于javascript - React JS音频不播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64448449/