can you convert music notes to midi file so the user can listen to the midi file, with pure javascript, without needing external libraries or other files? For example this: title: Cosmic Pulse
key: C minor
duration: 16
notation: |-
pitch,time,duration,velocity
60,0,0.75,100
63,1,0.5,90
65,1.75,0.25,85
67,2,1,110
65,3.25,0.5,95
63,4,0.75,100
60,5,0.5,90
58,5.75,0.25,85
60,6,1,110
63,7.25,0.5,95
65,8,0.75,100
67,9,0.5,90
68,9.75,0.25,85
70,10,1,110
68,11.25,0.5,95
67,12,0.75,100
65,13,0.5,90
63,13.75,0.25,85
60,14,2,110
Assistant
Yes, I can help you create a pure JavaScript program that converts the given music notes into a MIDI file, which the user can listen to. Below is a complete HTML file with embedded JavaScript that does exactly that. It parses the provided notation data, generates a MIDI file in binary format, and allows the user to download and play it.
html
<!DOCTYPE html>
<html>
<head>
<title>Cosmic Pulse MIDI Generator</title>
</head>
<body>
<h1>Cosmic Pulse MIDI Generator</h1>
<button onclick="generateMIDI()">Generate and Play MIDI</button>
<br><br>
<audio id="midiPlayer" controls></audio>
<script>
// Music data provided
const title = "Cosmic Pulse";
const key = "C minor";
const duration = 16;
const notation = `
pitch,time,duration,velocity
60,0,0.75,100
63,1,0.5,90
65,1.75,0.25,85
67,2,1,110
65,3.25,0.5,95
63,4,0.75,100
60,5,0.5,90
58,5.75,0.25,85
60,6,1,110
63,7.25,0.5,95
65,8,0.75,100
67,9,0.5,90
68,9.75,0.25,85
70,10,1,110
68,11.25,0.5,95
67,12,0.75,100
65,13,0.5,90
63,13.75,0.25,85
60,14,2,110
`;
// Function to generate MIDI file
function generateMIDI() {
// Parse the notation data
const lines = notation.trim().split('\n');
const header = lines.shift(); // Skip header
const notes = lines.map(line => {
const [pitch, time, duration, velocity] = line.split(',').map(Number);
return { pitch, time, duration, velocity };
});
// Function to write variable-length quantity
function vlq(value) {
let bytes = [];
do {
let byte = value & 0x7F;
value = value >> 7;
if (bytes.length > 0) byte |= 0x80;
bytes.unshift(byte);
} while (value > 0);
return bytes;
}
// MIDI header chunk
const headerChunk = [];
headerChunk.push(...[0x4D, 0x54, 0x68, 0x64]); // Chunk type 'MThd'
headerChunk.push(...[0x00, 0x00, 0x00, 0x06]); // Header length
headerChunk.push(...[0x00, 0x00]); // Format type 0
headerChunk.push(...[0x00, 0x01]); // Number of tracks
headerChunk.push(...[0x00, 0x60]); // Time division (96 ticks per quarter note)
// MIDI track chunk
let trackEvents = [];
// Set tempo (optional, default is 500000 microseconds per quarter note)
// Here we set it to 500,000 microseconds per quarter note (120 BPM)
trackEvents.push(0x00); // Delta time
trackEvents.push(0xFF, 0x51, 0x03, 0x07, 0xA1, 0x20); // Set Tempo
// Add note events
let lastTime = 0;
notes.forEach(note => {
const deltaTime = Math.round((note.time * 96) - lastTime);
lastTime += deltaTime;
const deltaTimeBytes = vlq(deltaTime);
// Note On event
trackEvents.push(...deltaTimeBytes);
trackEvents.push(0x90); // Note On, channel 0
trackEvents.push(note.pitch);
trackEvents.push(note.velocity);
// Note Off event
const noteOffDeltaTime = Math.round(note.duration * 96);
const noteOffDeltaTimeBytes = vlq(noteOffDeltaTime);
trackEvents.push(...noteOffDeltaTimeBytes);
trackEvents.push(0x80); // Note Off, channel 0
trackEvents.push(note.pitch);
trackEvents.push(0x00);
});
// End of Track event
trackEvents.push(0x00); // Delta time
trackEvents.push(0xFF, 0x2F, 0x00); // End of Track
// Track chunk header
const trackChunk = [];
trackChunk.push(...[0x4D, 0x54, 0x72, 0x6B]); // Chunk type 'MTrk'
const trackLength = trackEvents.length;
trackChunk.push(
(trackLength >> 24) & 0xFF,
(trackLength >> 16) & 0xFF,
(trackLength >> 8) & 0xFF,
trackLength & 0xFF
);
// Combine all data
const midiData = [...headerChunk, ...trackChunk, ...trackEvents];
// Convert to Uint8Array
const midiArray = new Uint8Array(midiData);
// Create Blob and URL
const blob = new Blob([midiArray], { type: "audio/midi" });
const url = URL.createObjectURL(blob);
// Set the audio player's source
const audioPlayer = document.getElementById('midiPlayer');
audioPlayer.src = url;
audioPlayer.play();
}
</script>
</body>
</html>
How it works:
Parsing the Notation Data: The JavaScript code begins by parsing the provided notation data into an array of note objects, each containing pitch, time, duration, and velocity.
Generating the MIDI File:
Header Chunk: The MIDI file starts with a header chunk that specifies the format, number of tracks, and time division.
Track Events:
Set Tempo Event: An optional event to set the tempo. In this example, it's set to 120 BPM.
Note On and Note Off Events: For each note, the code calculates the delta times and creates Note On and Note Off events. Delta times are converted into Variable Length Quantities (VLQ).
End of Track Event: Signals the end of the track.
Creating MIDI Data: The header chunk, track chunk, and track events are combined into a single array of bytes.
Playing the MIDI File:
Blob Creation: The byte array is converted into a Uint8Array, then into a Blob with the MIME type audio/midi.
Audio Element: The MIDI file blob is used as the source for an HTML5 audio element, which allows the user to play the generated MIDI file directly in the browser.
Usage Instructions:
Run the Code: Save the provided code into a file with an .html extension (e.g., cosmic_pulse.html).
Open in Browser: Open the HTML file in a modern web browser (e.g., Chrome, Firefox).
Generate MIDI: Click the "Generate and Play MIDI" button. The MIDI file will be generated, and playback will start automatically.
Control Playback: Use the audio controls to play, pause, or adjust the volume.
Notes:
Compatibility: Not all browsers support playing MIDI files directly in the <audio> element. If the MIDI doesn't play, you may need to use a browser extension or MIDI plugin that enables MIDI playback.
MIDI Support: For better compatibility, consider using the Web Audio API with a MIDI synthesizer, but that would require more complex code and possibly external libraries.
Extending the Code: You can modify the notation data to include more notes or change the tempo by adjusting the Set Tempo event.
Disclaimer: This code is written from scratch based on the MIDI file format specifications and is intended for educational purposes.