javascript - react js播放本地MP3文件
问题描述
在此处开发 reactJS-with-Electron 应用程序。我正在尝试从 redux reducer 播放本地 MP3 音乐文件(因为音乐需要跨多个页面播放)。
代码就像
const filePath = '../../resources/sound.mp3';
const newMusicRef = new Audio();
newMusicRef.loop = true;
newMusicRef.play().then(()=>{});
但是在运行时,应用程序从基本路径中查找应用程序的绝对路径 (/home/user/..) 而不是相对路径。我最终找不到一个文件。
然后我尝试使用
import sound from '../../resources/sound.mp3';
我得到了错误
client:159 ./app/resources/sounds/sound.mp3 1:3
Module parse failed: Unexpected character '' (1:3)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
为了播放这个本地文件,我怎样才能完成这项工作?
解决方案
你可以这样做。将您的路径粘贴到声音变量中。这是正在运行的示例,您可以尝试一下。
const sound = 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3';
function About() {
const [audio] = useState(new Audio(sound));
/*
* STOP AUDIO
*/
const stopAudio = () => {
audio.pause();
};
/*
* PLAY AUDIO ON HOVER
*/
const playAudio = () => {
audio.play();
};
return (
<span onMouseEnter={() => playAudio()} onMouseLeave={() => stopAudio()}>
audio
</span>
);
}
推荐阅读
- python - TypeError: 'str' 对象在使用 type() 函数时不可调用
- operating-system - 加载时内核卡住了重新启动
- python - 遍历嵌套的dict来获取数据
- c++ - 从可变参数类型生成函数类型转换中的参数类型
- java - Jar 存储库的原生查询方法中的 org.springframework.data.mapping.PropertyReferenceException
- javascript - Quasar Touch 滑动问题
- linux - 我的 Rust 单元测试中出现“来自索引 1 的 1 个字节的无效 utf-8 序列”和“munmup_chunk():无效指针”错误
- javascript - 无法使用for循环将二维数组的元素复制到另一个数组中
- pandas - 无法使用 Pandas 覆盖列值
- firebase - “对于每个项目,FCM 允许 2500 个并行连接”在 FCM 中是什么意思?