Creating a random sheet music generator in the browser using HTML, CSS, and JavaScript involves several components: generating random notes, structuring bars according to a time signature, choosing keys, and rendering the rhythm appropriately.
A full-featured sheet music renderer is complex, but we can create a basic implementation that:
- Generates random melody bars.
- Supports different time signatures.
- Uses a seed for randomness (optional).
- Shows note durations according to rhythm.
- Supports choosing musical keys.
- Displays notes and bars visually with simple text and CSS.
For better rendering of actual sheet music notation, libraries like VexFlow are excellent. I will provide a minimal example using VexFlow (a JavaScript library for rendering music notation) alongside random generation based on a seed, time signature, rhythm, and keys.
Features:
- User inputs: seed, time signature, key.
- Random notes generation according to the key.
- Rhythms picked randomly but fitting in a bar according to the time signature.
- Bars displayed with VexFlow.
Setup: Include VexFlow
<script src="https://unpkg.com/vexflow/releases/vexflow-min.js"></script>
Full Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Random Sheet Music Generator</title>
<style>
body { font-family: sans-serif; padding: 20px; max-width: 600px; margin: auto; }
label { display: block; margin-top: 10px; }
input, select, button { margin-top: 5px; }
#sheet { margin-top: 20px; border: 1px solid #ccc; padding: 10px; }
</style>
</head>
<body>
<h1>Random Sheet Music Generator</h1>
<label>
Seed (integer):
<input type="number" id="seedInput" value="123" />
</label>
<label>
Time Signature:
<select id="timeSigInput">
<option value="4/4">4/4</option>
<option value="3/4">3/4</option>
<option value="6/8">6/8</option>
</select>
</label>
<label>
Key:
<select id="keyInput">
<option value="C">C major</option>
<option value="G">G major</option>
<option value="D">D major</option>
<option value="A">A major</option>
<option value="E">E major</option>
<option value="F">F major</option>
<option value="Bb">B♭ major</option>
</select>
</label>
<label>
Number of Bars:
<input type="number" id="barsInput" value="4" min="1" max="16" />
</label>
<button id="generateBtn">Generate Music</button>
<div id="sheet"></div>
<script src="https://unpkg.com/vexflow/releases/vexflow-min.js"></script>
<script>
const VF = Vex.Flow;
// Simple seedable RNG (Mulberry32)
function mulberry32(a) {
return function() {
let t = a += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
}
// Note durations allowed
const durations = ['w', 'h', 'q', '8', '16']; // whole, half, quarter, eighth, sixteenth
// Their beat values in quarter notes
const durationValues = {
'w': 4,
'h': 2,
'q': 1,
'8': 0.5,
'16': 0.25,
};
// Notes in a C major scale (simplified)
const scaleNotes = {
'C': ['C', 'D', 'E', 'F', 'G', 'A', 'B'],
'G': ['G', 'A', 'B', 'C', 'D', 'E', 'F#'],
'D': ['D', 'E', 'F#', 'G', 'A', 'B', 'C#'],
'A': ['A', 'B', 'C#', 'D', 'E', 'F#', 'G#'],
'E': ['E', 'F#', 'G#', 'A', 'B', 'C#', 'D#'],
'F': ['F', 'G', 'A', 'Bb', 'C', 'D', 'E'],
'Bb': ['Bb', 'C', 'D', 'Eb', 'F', 'G', 'A'],
};
// Convert note with accidental to VexFlow format (e.g., Bb4)
// We'll keep the octave constant for simplicity (e.g., octave 4)
function getRandomNoteInKey(key, rng) {
const scale = scaleNotes[key];
const index = Math.floor(rng() * scale.length);
const noteName = scale[index];
return noteName + "4"; // octave 4 fixed
}
// Parse time signature string into numerator and denominator
function parseTimeSig(ts) {
const [num, den] = ts.split('/').map(Number);
return { num, den };
}
// Generate random rhythm fitting the bar length
function generateRhythm(barLengthQuarter, rng) {
// We'll pick random durations summing up to barLengthQuarter
// Try greedy: pick longest note <= remaining time randomly
const possibleDurations = durations.filter(d => durationValues[d] <= barLengthQuarter);
const result = [];
let remaining = barLengthQuarter;
while (remaining > 0.001) {
// Filter durations fitting in remaining time
const fits = durations.filter(d => durationValues[d] <= remaining);
if (fits.length === 0) break;
// For variation, pick randomly from fits
let dur = fits[Math.floor(rng() * fits.length)];
result.push(dur);
remaining -= durationValues[dur];
}
return result;
}
function createRandomBar(key, timeSig, rng) {
const { num, den } = timeSig;
// Calculate total bar length in quarter notes
const barLengthQuarter = num * (4 / den);
// Generate rhythm pattern that fits bar
const rhythm = generateRhythm(barLengthQuarter, rng);
// Generate notes according to rhythm
const notes = rhythm.map(dur => {
const noteName = getRandomNoteInKey(key, rng);
// VexFlow note format e.g. 'c/4', 'f#/4'
// Convert noteName like Bb4 to correct format and accidental
let letter = noteName[0].toLowerCase();
let accidental = null;
if (noteName.length === 3) {
accidental = noteName[1];
if (accidental === '#') accidental = '#';
else if (accidental === 'b') accidental = 'b';
else accidental = null;
letter = letter; // stays the same
}
// octave
let octave = noteName.slice(-1);
let vfNote = { keys: [`${letter}/${octave}`], duration: dur };
if (accidental) {
vfNote.accidental = accidental;
}
return vfNote;
});
return notes;
}
// Render bars with VexFlow
function renderBars(bars, timeSigString, keyString) {
const div = document.getElementById("sheet");
div.innerHTML = "";
// Create VF renderer
const renderer = new VF.Renderer(div, VF.Renderer.Backends.SVG);
// Make width 500px x height based on bars (each bar ~ 110px wide, 150px high)
const width = 120 * bars.length;
const height = 160;
renderer.resize(width, height);
const context = renderer.getContext();
const staveWidth = 110;
const staveY = 40;
const staveHeight = 80;
// Create stave for each bar
for (let i=0; i<bars.length; i++) {
let stave = new VF.Stave(i * staveWidth, staveY, staveWidth);
if (i === 0) {
stave.addClef("treble").addTimeSignature(timeSigString).addKeySignature(keyString);
}
stave.setContext(context).draw();
const vfNotes = bars[i].map(note => {
let n = new VF.StaveNote({ keys: note.keys, duration: note.duration });
if (note.accidental) {
n.addAccidental(0, new VF.Accidental(note.accidental));
}
// Add dots if needed for dotted durations (optional). Not implemented here for simplicity
return n;
});
// Create voice
const voice = new VF.Voice({ num_beats: parseInt(timeSigString.split('/')[0]), beat_value: parseInt(timeSigString.split('/')[1]) });
voice.addTickables(vfNotes);
// Format and Draw
const formatter = new VF.Formatter().joinVoices([voice]).format([voice], staveWidth - 10);
voice.draw(context, stave);
}
}
function generateMusic() {
let seed = parseInt(document.getElementById('seedInput').value) || Date.now();
let rng = mulberry32(seed);
let timeSigString = document.getElementById('timeSigInput').value;
let keyString = document.getElementById('keyInput').value;
let barsCount = parseInt(document.getElementById('barsInput').value) || 4;
let timeSig = parseTimeSig(timeSigString);
// Generate bars
let bars = [];
for(let i=0; i<barsCount; i++) {
bars.push(createRandomBar(keyString, timeSig, rng));
}
renderBars(bars, timeSigString, keyString);
}
document.getElementById('generateBtn').addEventListener('click', generateMusic);
// Initial render
generateMusic();
</script>
</body>
</html>
How it works
- You enter a seed (integer) to get reproducible results.
- Time signature and key select the rules for the generated music.
- Number of bars controls how many bars are generated.
- Clicking generate will produce random notes on the staff fitting each bar's length according to the time signature.
- Notes are selected from the selected key.
- The rhythm is randomly chosen but always fits the time signature.
Notes / Improvements
- Currently octave is fixed at 4, which you can randomize.
- Rhythm durations slot sums exactly to bar length, but no ties/dots yet.
- Accidentals only simple sharps/flats from key scale; no chromatic notes.
- You can improve with more complex rhythm/note generation, slurs, rests, dynamics.
- VexFlow is very powerful and supports much more (chords, rests, beams...).
Let me know if you want me to add more features like rests, dotted rhythms, multiple voices, etc!