WWW FAQs: How do I play a MIDI file on my web page?


2007-05-29: General MIDI files (.mid files) are not the most popular way to distribute music on the web, and there are good reasons for that. General MIDI offers a limited range of instrument sounds, there are no vocals, and the end result almost always sounds... well, a bit like a toy piano.

But good General MIDI tracks do exist. And MIDI does have the advantage of very small file size. That's because the file specifies the notes and instruments rather than recording the actual sounds.

"Why do you keep calling it 'General' MIDI?"

By itself, MIDI (Musical Instrument Digital Interface) doesn't specify any standard instrument sounds. The "General MIDI" specification adds standardized instruments so that a MIDI file made with one computer can be played back with predictable results on another computer— the piano will still be a piano, the guitar will still be a guitar.

These days, the most popular solution for music in web pages is the MP3 file. And Flash supports MP3 files. So most webmasters simply use a Flash-based player as described in my article how do I embed sound and music in a page?

Unfortunately, Flash won't do MIDI. But there's another solution that does work for MIDI. We can embed the MIDI player directly in the page, via the object element:


<object data="mysong.mid">
<param name="loop" value="10"/>
If you're seeing this, you don't have a MIDI player
on your computer.
</object>

This HTML code will embed the MIDI file mysong.mid directly in the page. This code assumes that mysong.mid is in the same folder with the web page. If not, just adjust the URL in the data attribute, just as you would if you were linking to another page.

The param name="loop" element specifies how many times the song will repeat. By setting the value attribute to 10, we repeat the song ten times.

Drawbacks of Embedded MIDI

Unfortunately, not everyone has a MIDI player. And even if they do, not every web browser is set up to embed that player. Be aware that a small fraction of users will not be able to hear your MIDI music.

Also, there is no reliable way to control the MIDI player from JavaScript. So we can't build our own "pause" or "rewind" buttons. So if you really want advanced features, I recommend embedding MP3 files via a Flash-based player instead.

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!