File size: 1,632 Bytes
d6517e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"use client";
import { useEffect, useRef, useState } from 'react';
import MidiPlayer from 'midi-player-js';
import Soundfont from 'soundfont-player';

export default function Home() {
  const audioCtx = useRef(new (window.AudioContext || (window as any).webkitAudioContext)());
  const instrument = useRef<any>(null);
  const player = useRef<any>(null);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    Soundfont.instrument(audioCtx.current, 'acoustic_grand_piano').then(inst => {
      instrument.current = inst;
      player.current = new MidiPlayer.Player(event => {
        if (event.name === 'Note on' && event.velocity > 0) instrument.current.play(event.noteName);
        if (event.name === 'Note off' || (event.name === 'Note on' && event.velocity === 0)) instrument.current.stop(event.noteName);
      });
      setLoaded(true);
    });
    return () => audioCtx.current.close();
  }, []);

  const loadMidi = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = () => player.current.loadArrayBuffer(reader.result);
      reader.readAsArrayBuffer(file);
    }
  };

  return (
    <main style={{padding:"2rem",fontFamily:"sans-serif"}}>

      <h1>MIDI Player Lite</h1>

      {loaded ? <input type="file" accept=".mid,.midi" onChange={loadMidi}/> : "Loading..."}

      <button onClick={() => player.current.play()} disabled={!loaded}>Play</button>

      <button onClick={() => player.current.stop()} disabled={!loaded}>Stop</button>

    </main>
  );
}