Creating a random sheet music generator with bars, seed, time signature, rhythm, keys, and both treble and bass clefs is a moderately complex but fun project! Below is a simplified example using HTML, CSS, and JavaScript leveraging the VexFlow library — a powerful tool for rendering music notation in the browser.
What this example will do:
- Generate a random seed for repeatability.
- Randomly pick a time signature.
- Generate random rhythms according to the time signature.
- Render a simple staff with treble and bass clefs.
- Show multiple bars/measures.
- Use a random key signature.
- Output music notation using VexFlow.
Steps:
- Include VexFlow library.
- Create controls to generate music with:
- Seed
- Time Signature
- Key Signature
- Draw treble and bass clefs.
- Generate notes with simple rhythms based on time signature.
- Render onto the canvas.
Code Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Random Sheet Music Generator</title>
<style>
body {
font-family: sans-serif;
margin: 30px;
background: #fafafa;
}
#container {
display: flex;
flex-direction: column;
align-items: center;
}
canvas {
border: 1px solid #ccc;
background: white;
}
label, select, input {
margin: 10px;
}
</style>
</head>
<body>
<div id="container">
<h1>Random Sheet Music Generator</h1>
<label for="seed">Seed: </label>
<input type="number" id="seed" value="1" min="1" max="9999" />
<label for="timeSignature">Time Signature: </label>
<select id="timeSignature">
<option value="4/4">4/4</option>
<option value="3/4">3/4</option>
<option value="6/8">6/8</option>
</select>
<label for="keySignature">Key Signature: </label>
<select id="keySignature">
<option value="C">C</option>
<option value="G">G</option>
<option value="D">D</option>
<option value="A">A</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="Bb">Bb</option>
<option value="Eb">Eb</option>
</select>
<button id="generate">Generate</button>
<div id="vexflow-container"></div>
</div>
<!-- Include VexFlow CDN -->
<script src="https://unpkg.com/vexflow/releases/vexflow-min.js"></script>
<script>
const VF = Vex.Flow;
// Simple PRNG with seed (Mulberry32)
function mulberry32(a) {
return function() {
var 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;
}
}
// Map note durations to ticks (for VexFlow)
const durationValues = ['w', 'h', 'q', '8', '16'];
// Possible notes in C major scale (wildly simplified)
// For treble: middle C = C4, bass typically down an octave
const trebleNotes = ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4'];
const bassNotes = ['E2', 'F2', 'G2', 'A2', 'B2', 'C3', 'D3'];
// Rhythms by time signature (simplify):
const rhythmPatterns = {
"4/4": ['q', 'q', 'q', 'q', 'h', 'h', 'q', '8 8'],
"3/4": ['q', 'q', 'q', 'h', 'q', '8 8', 'q h', '8 8 8'],
"6/8": ['8 8 8 8 8 8', 'q 8 8', 'h q', '8 8 8 q']
};
// Helper: choose from array randomly
function choice(arr, rng) {
return arr[Math.floor(rng() * arr.length)];
}
// Generate measure notes based on time signature and seed (rng)
function generateMeasure(timeSig, rng) {
const patterns = rhythmPatterns[timeSig];
let patternStr = choice(patterns, rng); // e.g. "q 8 8"
let durations = patternStr.split(' ');
// Generate notes for each duration
let notes = durations.map(dur => {
// Random note from treble notes (rotate to keys later)
let note = choice(trebleNotes, rng);
return { keys: [note.toLowerCase()], duration: dur };
});
return notes;
}
// Generate bass measure matching rhythmic pattern for simplicity
function generateBassMeasure(timeSig, rng) {
const patterns = rhythmPatterns[timeSig];
let patternStr = choice(patterns, rng);
let durations = patternStr.split(' ');
let notes = durations.map(dur => {
let note = choice(bassNotes, rng);
return { keys: [note.toLowerCase()], duration: dur };
});
return notes;
}
// Rotate notes according to key signature (simplified major scales)
const keyScales = {
'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'],
'Eb': ['Eb', 'F', 'G', 'Ab', 'Bb', 'C', 'D']
};
// Convert note string to match key signature:
// E.g. C4 to C#4 if key signature has sharps/flats
function transposeNoteByKey(noteStr, key) {
// noteStr: e.g. c4
let scale = keyScales[key];
if (!scale) scale = keyScales['C'];
// Extract letter and octave
let letter = noteStr[0].toUpperCase();
let accidental = '';
let octave = noteStr.slice(-1);
if (noteStr.length === 3) accidental = noteStr[1]; // e.g. 'b' or '#'
// Find letter index in C major scale
const cMajor = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];
let idx = cMajor.indexOf(letter);
if (idx === -1) return noteStr;
// Replace letter with key's scale note at same position
let target = scale[idx];
// Target can have accidental: e.g. F# or Bb
let targetLetter = target[0];
let targetAcc = target.length === 2 ? target[1] : '';
return (targetLetter.toLowerCase() + targetAcc + octave);
}
// Generate the full sheet music
function generateSheet(seed, timeSignature, keySignature) {
const rng = mulberry32(seed);
const container = document.getElementById('vexflow-container');
container.innerHTML = ''; // Clear previous
// Create renderer
const div = document.createElement('div');
container.appendChild(div);
const renderer = new VF.Renderer(div, VF.Renderer.Backends.SVG);
renderer.resize(900, 250);
const context = renderer.getContext();
// Dimensions and position vars
const staveWidth = 400;
const staveMargin = 20;
// Create two staves — treble and bass
let staveTreble = new VF.Stave(staveMargin, 40, staveWidth);
staveTreble.addClef('treble').addTimeSignature(timeSignature).addKeySignature(keySignature);
staveTreble.setContext(context).draw();
let staveBass = new VF.Stave(staveMargin, 120, staveWidth);
staveBass.addClef('bass').addTimeSignature(timeSignature).addKeySignature(keySignature);
staveBass.setContext(context).draw();
// Create one more stave to simulate measures repeat (optional)
const staveMargin2 = staveMargin + staveWidth + 20;
let staveTreble2 = new VF.Stave(staveMargin2, 40, staveWidth);
staveTreble2.addClef('treble').addTimeSignature(timeSignature).addKeySignature(keySignature);
staveTreble2.setContext(context).draw();
let staveBass2 = new VF.Stave(staveMargin2, 120, staveWidth);
staveBass2.addClef('bass').addTimeSignature(timeSignature).addKeySignature(keySignature);
staveBass2.setContext(context).draw();
// Generate notes for two measures (treble & bass)
let trebleNotes1 = generateMeasure(timeSignature, rng);
let bassNotes1 = generateBassMeasure(timeSignature, rng);
let trebleNotes2 = generateMeasure(timeSignature, rng);
let bassNotes2 = generateBassMeasure(timeSignature, rng);
// Transpose notes by key
function transposeNotes(notes) {
return notes.map(n => {
let keys = n.keys.map(noteStr => transposeNoteByKey(noteStr, keySignature));
return new VF.StaveNote({clef: 'treble', keys: keys, duration: n.duration});
});
}
function transposeBassNotes(notes) {
return notes.map(n => {
let keys = n.keys.map(noteStr => transposeNoteByKey(noteStr, keySignature));
return new VF.StaveNote({clef: 'bass', keys: keys, duration: n.duration});
});
}
// Helper to add accidentals if needed
function addAccidentals(notes) {
notes.forEach(note => {
note.keys.forEach((key, idx) => {
if (key.includes('#')) note.addAccidental(idx, new VF.Accidental('#'));
if (key.includes('b')) note.addAccidental(idx, new VF.Accidental('b'));
});
});
}
let vfTrebleNotes1 = transposeNotes(trebleNotes1);
let vfBassNotes1 = transposeBassNotes(bassNotes1);
let vfTrebleNotes2 = transposeNotes(trebleNotes2);
let vfBassNotes2 = transposeBassNotes(bassNotes2);
addAccidentals(vfTrebleNotes1);
addAccidentals(vfBassNotes1);
addAccidentals(vfTrebleNotes2);
addAccidentals(vfBassNotes2);
// Create voice and add tickables for measure 1 treble
let voiceTreble1 = new VF.Voice({num_beats: parseInt(timeSignature.split('/')[0]), beat_value: parseInt(timeSignature.split('/')[1])});
voiceTreble1.addTickables(vfTrebleNotes1);
let voiceBass1 = new VF.Voice({num_beats: parseInt(timeSignature.split('/')[0]), beat_value: parseInt(timeSignature.split('/')[1])});
voiceBass1.addTickables(vfBassNotes1);
let voiceTreble2 = new VF.Voice({num_beats: parseInt(timeSignature.split('/')[0]), beat_value: parseInt(timeSignature.split('/')[1])});
voiceTreble2.addTickables(vfTrebleNotes2);
let voiceBass2 = new VF.Voice({num_beats: parseInt(timeSignature.split('/')[0]), beat_value: parseInt(timeSignature.split('/')[1])});
voiceBass2.addTickables(vfBassNotes2);
// Format and justify the notes to the stave's width
const formatter = new VF.Formatter();
formatter.joinVoices([voiceTreble1]).format([voiceTreble1], staveWidth - 50);
formatter.joinVoices([voiceBass1]).format([voiceBass1], staveWidth - 50);
formatter.joinVoices([voiceTreble2]).format([voiceTreble2], staveWidth - 50);
formatter.joinVoices([voiceBass2]).format([voiceBass2], staveWidth - 50);
// Draw voices
voiceTreble1.draw(context, staveTreble);
voiceBass1.draw(context, staveBass);
voiceTreble2.draw(context, staveTreble2);
voiceBass2.draw(context, staveBass2);
}
document.getElementById('generate').addEventListener('click', () => {
const seed = parseInt(document.getElementById('seed').value) || 1;
const timeSig = document.getElementById('timeSignature').value;
const keySig = document.getElementById('keySignature').value;
generateSheet(seed, timeSig, keySig);
});
// Generate initial sheet on load
window.onload = () => {
document.getElementById('generate').click();
};
</script>
</body>
</html>
How it works:
- The user chooses a seed number; this controls randomness so the same seed yields the same music.
- The user selects a time signature (e.g., 4/4, 3/4, 6/8).
- The user selects a key signature.
- Clicking "Generate" generates two measures (bars) of random note rhythms for treble and bass clefs.
- Notes are transposed to the selected key.
- VexFlow draws the staves with clefs, key/time signatures, and the notes rhythmically aligned.
Next steps to extend:
- Incorporate more musical realism (e.g., proper harmonic progression).
- Add multiple voices or chords.
- Implement rests and ties.
- Export to MIDI or MusicXML.
- Add user interface to select instruments or rhythmic complexity.
If you'd like me to help build on this with more advanced features or explain parts of the code in detail, feel free to ask!