React-Sound不会播放项目文件夹中的mp3文件

时间:2019-03-07 23:27:32

标签: javascript reactjs audio jsx

在尝试构建钢琴应用程序并做到这一点之前,我一直在考虑使用react-sound。单击按钮后,我想播放一些mp3声音。但是,由于某些原因,尽管我根据react-sound库中的手册创建了一个单独的Tune组件,但仍无法播放声音。控制台中也没有特定的错误。单击特定键后,应该触发声音console.logs数据的方法,因此我怀疑按钮交互正常。有人遇到过该软件包问题吗?

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Key from './Components/Key.js';
import Tone from './Components/Tone.js';

class App extends Component {
  state = {
   combinationsOfKeys: [
  {'A': [0,7]},
  {'Ab' : [1,7]},
  {'B': [0,7]},
  {'Bb': [0.7]},
  {'C': [1,8]},
  {'D': [1,7]},
  {'Db': [1,8]},
  {'E': [1,7]},
  {'Eb': [1,7]},
  {'F': [1,7]},
  {'G': [1,7]},
  {'Gb': [1,7]}
]
}

 handlePlayingMp3File = (fileId) => {
   console.log('Clicked'+ fileId)
   return (
  <Tone keyName={fileId}/>
  )
}

render() {
const keys = []
const namesOfKeys = []

for(let i=0; i<this.state.combinationsOfKeys.length; i++){
  let nameOfMp3File = ''
  let currentObject = this.state.combinationsOfKeys[i];
  let keyOfTheObject = Object.keys(currentObject)
  let valueOfTheObjectArrayWithKeyLimits = currentObject[keyOfTheObject[0]]
  for(let n = valueOfTheObjectArrayWithKeyLimits[0];
    n < valueOfTheObjectArrayWithKeyLimits[1]+1; n++){
      nameOfMp3File = keyOfTheObject + n + '.mp3'
      namesOfKeys.push(nameOfMp3File)
    }
};

console.log(this.state.combinationsOfKeys.length)
for(let i=0; i<namesOfKeys.length; i++){
  let nameOfAnMP3File = namesOfKeys[i];
  keys.push(<Key
    key={i}
    keyName={nameOfAnMP3File.replace('.mp3', '')}
    fileName={nameOfAnMP3File}
    playMusic={() => this.handlePlayingMp3File(nameOfAnMP3File)}/>)
}
return (
  <div>
    {keys}
  </div>
);
}}

export default App;

以及带有Key组件的Tone组件

import React, { Component } from 'react';
import Sound from 'react-sound'

class Tone extends Component {

constructor(props){
  super(props);
}

render() {
 return (
   <Sound
   url='/piano-keys-sounds/A1.mp3'
   playStatus={Sound.status.PLAYING}
   />
  );
 }
}

export default Tone;

import React, {Component} from 'react'
import Sound from 'react-sound';

const key = (props) => {
  return (
    <button onClick={props.playMusic}>{props.keyName}</button>
  )
}

export default key;

2 个答案:

答案 0 :(得分:1)

我看不到您导入任何mp3文件。

我这样做是没有反应音的:

import React, { useState } from "react";
import sound1 from "../audio/sound1.wav";

const Example = () => {

  const [playSound, setPlaySound] = useState(0);

  return (
    <div>
      <button onClick={() => setPlaySound(!playSound)}>Toggle</button>
      {playSound ? <audio src={shuffle1} autoPlay /> : null}
    </div>
  );
};

export default Example;

答案 1 :(得分:0)

我将文件放在公用文件夹中,对我来说很好用。