首先,安装正确的依赖:
npm install @magenta/music
然后,在您的React
代码中,执行以下操作:
import React from "react";
import * as mm from "@magenta/music/es6";
class App extends React.Component {
constructor(props) {
super(props);
this.TWINKLE_TWINKLE = {
notes: [
{ pitch: 60, startTime: 0.0, endTime: 0.5 },
{ pitch: 60, startTime: 0.5, endTime: 1.0 },
{ pitch: 67, startTime: 1.0, endTime: 1.5 },
{ pitch: 67, startTime: 1.5, endTime: 2.0 },
{ pitch: 69, startTime: 2.0, endTime: 2.5 },
{ pitch: 69, startTime: 2.5, endTime: 3.0 },
{ pitch: 67, startTime: 3.0, endTime: 4.0 },
{ pitch: 65, startTime: 4.0, endTime: 4.5 },
{ pitch: 65, startTime: 4.5, endTime: 5.0 },
{ pitch: 64, startTime: 5.0, endTime: 5.5 },
{ pitch: 64, startTime: 5.5, endTime: 6.0 },
{ pitch: 62, startTime: 6.0, endTime: 6.5 },
{ pitch: 62, startTime: 6.5, endTime: 7.0 },
{ pitch: 60, startTime: 7.0, endTime: 8.0 },
],
totalTime: 8,
};
this.player = new mm.Player();
}
play = () => {
if (this.player.isPlaying()) {
return;
}
this.player.start(this.TWINKLE_TWINKLE);
};
render() {
return (
<div>
<button type="button" onClick={this.play}>
Play!
</button>
</div>
);
}
}