当用户点击Button时,我想在React中播放mp3。 这只是一个测试,我有两个文件:App.js和Audio.js。
音频包含类声音并返回一个Button。 我在App.js中导入了它。
App.js
import React, { Component } from 'react';
import img from './assets/image/img1.png';
import './App.css';
import ReactDOM from 'react-dom';
import Sounds from './components/Audio'
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={ img } className="imgDino" alt="a cool dinosaure" />
<Sounds />
</header>
</div>
);
}
}
export default App;
Audio.js
import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
class Sounds extends React.Component {
constructor(props) {
super(props);
this.state = { play: false };
this.src = './assets/sound/sound1.mp3';
this.audio = new Audio(this.src);
this.play = this.play.bind(this);
}
play() {
this.setState({ play: this.state.play });
console.log(this.audio);
this.state.play = this.audio.play();
}
render() {
return (
<div>
<Button onClick={ this.play }>{ 'ROAAR!' }</Button>
</div>
);
}
}
export default Sounds;
控制台说:
<audio preload="auto" src="./assets/sound/sound1.mp3">
没问题,但我没有声音。