JS MOD player

#retrocomputing #javascript #demoscene

Written by Anders Marzi Tornblad

This is a MOD player, developed in vanilla JavaScript using modern (2022) Web Audio and Audio Worklet APIs.

Try it out live on my GitHub page.

Read about how it was made in my blog post series.

Licence: Creative Commons Attribution-NonCommercial 4.0 International License

Getting started

Add the following JavaScript files from this GitHub repository to your own project:

Add a Protracker 2.3 compatible MOD file to your project.

Add the following script element to your html file:

<script type="module">
    import { ModPlayer } from './player.js';
    const player = new ModPlayer();
    await player.load('./my-mod-file.mod');
    window.addEventListener('click', async () => {
        await player.play();
    });
</script>
Script tag for loading and starting the player

This will create an instance of the ModPlayer class and load the MOD file. When the user clicks the window, the music will start to play. Web Audio API does not allow audio to play until the user has interacted with the page, so you have to wait for wome type of user input, like a click or a tap.

Event system

To use music as a time source, or for synchronizing effects and events in a demo, you can use the watch and watchRows methods to get notified at the exact moment different rows are played.

Examples

// Calls the switchToNextScene method when the music 
// reaches row 16 in position 4
player.watch(4, 16, switchToNextScene);

// Calls the flashTheScreen method every 4 rows
player.watchRows((pos, row) => {
    if ((row % 4) === 0) {
        flashTheScreen();
    }
});
Examples of reacting to music events

Specifications

For complete specifications, please visit the GitHub repository.

You can try this solution at atornblad.github.io/js-mod-player. The latest version of the code is always available in the GitHub repository.