JS MOD player
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 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 'https://atornblad.se/files/js-mod-player/player.js';
const audio = new AudioContext();
const player = new ModPlayer(audio);
await player.load('./my-mod-file.mod');
window.addEventListener('click', async () => {
player.play();
});
</script>
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();
}
});
Specifications
Public methods of the ModPlayer
class:
async load(url)
Loads a MOD file from a url.unload()
Unloads a loaded MOD file and frees resources.play()
Starts playing music.stop()
Stops playing.resume()
Resumes playing after a call tostop()
setVolume(volume)
Sets the volume of an internal gain node. Default value: 0.3setRow(position, row)
Jumps to a specific time in the music.watch(position, row, callback)
Registers a callback for a position and row.watchRows(callback)
Registers a callback for all rows.
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.