Play MIDI files in a browser with a simple Web Component, emulating
<bgsound>
, the Background Sound element.
npm install bg-sound timidity freepats
<bg-sound src="sound.mid"></bg-sound>
<script src="bg-sound.min.js"></script>
I introduced this project in a talk at JSConf Colombia 2018.
- Slides
- Talk video (coming soon!)
The name of a custom HTML element must contain a dash (-). This is what the spec says, presumably because otherwise browsers could not introduce new HTML tags without web compatibility risk.
The script tag is needed to define the behavior of the <bg-sound>
HTML element. Without it, the browser would just treat the tag like a <div>
.
The <bg-sound>
custom element lazily loads a WebAssembly file and instrument
sounds at runtime.
The timidity
package provides the WebAssembly file (libtimidity.wasm
). The
freepats
package provides the instrument sound files.
It's important to ensure that the timidity
and freepats
folders in
node_modules
are being served to the public. For example, here is how to mount
the necessary files at /
with the express
server:
const timidityPath = path.dirname(require.resolve('timidity'))
app.use(express.static(timidityPath))
const freepatsPath = path.dirname(require.resolve('freepats'))
app.use(express.static(freepatsPath))
Optionally, provide a baseUrl
attribute to customize where the player will
look for the lazy-loaded WebAssembly file libtimidity.wasm
and the
FreePats General MIDI soundset files.
The default baseUrl
is /
.
<bg-sound src="sound.mid" baseUrl="/custom-path"></bg-sound>
If you like this, then check out BitMidi.com, the wayback machine for old-school MIDI files! Check out some examples MIDIs here:
- Adele - Skyfall
- Beatles - Imagine
- Beyonce - Crazy in Love
- CANYON.MID
- Cowboy Bepop - Space Lion
- Eiffel 65 - Blue
- Kingdom Hearts - Dearly Beloved
- Mario Bros. - Super Mario Bros. Theme
- Passenger - Let Her Go
- Portal - Still Alive
- Rick Astley - Never Gonna Give You Up
- Simpsons Theme Song
- Sonic the Hedgehog - Green Hill Zone
- TOTO - Africa
MIT. Copyright (c) Feross Aboukhadijeh.