简体   繁体   English

react js播放本地MP3文件

[英]react js playing local MP3 file

Developing a reactJS-with-Electron app here.在此处开发 reactJS-with-Electron 应用程序。 I am trying to play a local MP3 music file from a redux reducer (because the music needs to play cross multiple pages).我正在尝试从 redux 减速器播放本地 MP3 音乐文件(因为音乐需要跨多个页面播放)。

The code is like代码就像

 const filePath = '../../resources/sound.mp3';
 const newMusicRef = new Audio();
 newMusicRef.loop = true;
 newMusicRef.play().then(()=>{});

But when running, the app is looking from the base path as the app's absolute path (/home/user/..) instead of the relative path.但是在运行时,应用程序从基本路径中查找应用程序的绝对路径 (/home/user/..) 而不是相对路径。 I end up with a file not found.我最终找不到一个文件。

I then tried using然后我尝试使用

import sound from '../../resources/sound.mp3';

I got error as我得到了错误

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)

How can I got either of this work, in order to play this local file?为了播放这个本地文件,我怎样才能得到这两项工作?

you can do like this.你可以这样做。 paste your path in sound variable.将您的路径粘贴到声音变量中。 this is running example you can try this.这是正在运行的示例,您可以尝试一下。

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>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM