Creating a random sheet music generator with configurable bars, seed (for repeatability), time signature, rhythm, and keys is an interesting project! Below is a simple implementation in HTML, CSS, and JavaScript that:
Generates random notes based on a given seed
Supports customizable bars and time signatures (like 4/4, 3/4)
Supports selection of key signatures (C, G, F major)
Shows the written notes in a basic staff using Unicode musical symbols for simplicity
This is a minimal, didactic example — for a more professional display you might integrate with music notation libraries like VexFlow or OpenSheetMusicDisplay.
Features in this example:
User inputs:
Number of bars
Time signature (beats per bar and beat unit)
Key signature (C, G, F major)
Seed for repeatable random generation
Generates random rhythmic patterns fitting the time signature per bar
Shows notes in the chosen key on a simplified staff
Uses deterministic random generator with seed for reproducibility
Here's the complete code:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Random Sheet Music Generator</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 1em;
}
label {
display: inline-block;
width: 100px;
}
input, select {
margin-bottom: 10px;
}
#sheet {
margin-top: 20px;
white-space: pre-wrap;
font-family: 'Courier New', monospace;
border: 1px solid #aaa;
padding: 1em;
background: #f9f9f9;
}
.staff-line {
font-size: 24px;
line-height: 1.2em;
}
.note {
display: inline-block;
width: 1.5em;
text-align: center;
}
</style>
</head>
<body>
<h1>Random Sheet Music Generator</h1>
<div>
<label for="bars">Bars:</label>
<input type="number" id="bars" min="1" max="16" value="4" />
</div>
<div>
<label for="beats">Beats per bar:</label>
<input type="number" id="beats" min="1" max="12" value="4" />
</div>
<div>
<label for="beatUnit">Beat unit:</label>
<select id="beatUnit">
<option value="4" selected>Quarter note (4)</option>
<option value="8">Eighth note (8)</option>
<option value="2">Half note (2)</option>
<option value="1">Whole note (1)</option>
</select>
</div>
<div>
<label for="key">Key:</label>
<select id="key">
<option value="C" selected>C Major</option>
<option value="G">G Major (F#)</option>
<option value="F">F Major (Bb)</option>
</select>
</div>
<div>
<label for="seed">Seed:</label>
<input type="text" id="seed" placeholder="Optional seed" />
</div>
<button id="generateBtn">Generate</button>
<div id="sheet"></div>
<script>
// Helper: seeded random
function mulberry32(seed) {
return function() {
let t = seed += 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 keys to accidentals
const KEY_SIGNATURES = {
'C': [],
'G': ['F#'],
'F': ['Bb']
};
// Notes in an octave
// We'll use the treble clef range from middle C (C4) up to B4
const NOTES = [
'C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4'
];
// Apply sharps/flats for selected key
// Returns array of note names adjusted for key signature
function applyKey(accidentals, note) {
// accidentals like 'F#' or 'Bb'
if (accidentals.length === 0) return note;
let baseNote = note[0];
if (note.length === 3) {
baseNote += note[1]; // e.g. 'Bb' has two letters, 2nd char is accidental
}
for (let acc of accidentals) {
if (acc[0] === baseNote) {
// replace note accidental with key accidental
// e.g. note F4 + F# => F#4
let accidental = acc[1]; // '#' or 'b'
return baseNote + accidental + note.slice(-1);
}
}
return note; // no accidental change
}
// Rhythms: notes with duration in beats
// Duration values relate to beat unit => quarter note 1, half 2, etc.
// We'll define durations as fraction of one bar beat length
// For simplicity generate rhythm values that sum exactly to beats per bar
const RHYTHM_VALUES = [
{ name: 'whole', durationFraction: 1 },
{ name: 'half', durationFraction: 0.5 },
{ name: 'quarter', durationFraction: 0.25 },
{ name: 'eighth', durationFraction: 0.125 },
// You can expand more if needed
];
// Unicode musical notes to represent different durations
// Using a simplified approach:
// ♩ = quarter note U+2669, ♪ = eighth note U+266A, etc.
const DURATION_SYMBOLS = {
'whole': '\u1D15D', // Musical Symbol Whole Note (𝅝) - may not render in all fonts
// If not supported, fallback to normal notes
'half': '\u266A', // ♪ as placeholder
'quarter': '\u2669', // ♩
'eighth': '\u266A', // ♪
};
// We'll fallback to ♩ for durations we can't display. Some Unicode music symbols may not render
// For simplicity, render note letter and duration symbol
// Generate random rhythms that fit into beats per bar * (beatUnit / 4)
// For example in 4/4 time, with beatUnit quarter = 4, measures 4 beats = 4 quarter notes total duration
// We generate a sequence of durations summing to beats per bar
// To map beat units to a proportion of a whole note (1), for now just use beats and duration fractions
function generateRhythm(beatsPerBar, beatUnit, rng) {
const totalBeats = beatsPerBar * (4 / beatUnit); // normalize to quarter notes for simplicity
// We'll generate rhythmic values summing to totalBeats
// For instance, totalBeats=4 for 4/4, possible rhythms: 1 whole, 2 half, 4 quarter, mixed
const rhythms = [];
let sum = 0;
while (sum < totalBeats) {
// pick a rhythm value that fits in remaining time
let remaining = totalBeats - sum;
// filter possible rhythms that fit
let candidates = RHYTHM_VALUES.filter(r => r.durationFraction <= remaining);
if (candidates.length === 0) break; // no fit
// choose randomly among candidates
let choice = candidates[Math.floor(rng() * candidates.length)];
rhythms.push(choice);
sum += choice.durationFraction;
}
return rhythms;
}
// Generate note pitch for given key signature and last note (to keep melody flowing)
// For simplicity pick any note randomly each time
function generateNote(rng, key) {
// Randomly pick among possible notes of scale
// We'll consider major scale notes only for simplicity
// Major scales: C D E F G A B
// Keys:
// C major (no accidentals)
// G major (F#)
// F major (Bb)
// Base notes in scale
const scaleDegrees = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];
// We'll generate random scale degree index
let index = Math.floor(rng() * scaleDegrees.length);
let baseNote = scaleDegrees[index];
// octave fixed at 4
// check accidentals
let accidentals = KEY_SIGNATURES[key];
let noteName = baseNote + '4';
noteName = applyKey(accidentals, noteName);
return noteName;
}
// Render sheet music textually
// For simplicity, lines represent notes + duration symbols
function renderSheet(barsArr, beatsPerBar, beatUnit) {
// barsArr is array of arrays: each bar contains objects { note, duration }
// We'll render bars separated by | bars
// For each bar, concat note names and duration symbols
// Compose a string with bar measures
let lines = [];
// Header: Time signature and key signature
lines.push(`Time Signature: ${beatsPerBar}/${beatUnit}, Bars: ${barsArr.length}`);
lines.push('');
// Render each bar
for (let i=0; i < barsArr.length; i++) {
let bar = barsArr[i];
let barStr = '| ';
for (let n of bar) {
// note string e.g. C4, F#4
let noteStr = n.note.slice(0, n.note.length - 1); // chop octave for brevity
// visuals could be improved to show sharps/flats with ♯/♭
noteStr = noteStr.replace('#', '♯').replace('b', '♭');
// duration symbol, use quarter note as fallback
let durSym = DURATION_SYMBOLS[n.duration.name] || '\u2669'; // ♩
barStr += noteStr + durSym + ' ';
}
barStr += '|';
lines.push(barStr);
}
return lines.join('\n');
}
function hashStringToNumber(str) {
let hash = 0;
for (let i=0; i<str.length; i++) {
hash = (hash << 5) - hash + str.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return Math.abs(hash);
}
document.getElementById('generateBtn').addEventListener('click', () => {
const bars = parseInt(document.getElementById('bars').value);
const beatsPerBar = parseInt(document.getElementById('beats').value);
const beatUnit = parseInt(document.getElementById('beatUnit').value);
const key = document.getElementById('key').value;
const seedInput = document.getElementById('seed').value.trim();
let seed;
if (seedInput.length > 0) {
seed = hashStringToNumber(seedInput);
} else {
seed = Math.floor(Math.random() * 1000000);
}
const rng = mulberry32(seed);
let barsArr = [];
for (let i=0; i<bars; i++) {
// generate rhythm for this bar
const rhythms = generateRhythm(beatsPerBar, beatUnit, rng);
// generate notes matching rhythm durations
let notesInBar = [];
for (let r of rhythms) {
let note = generateNote(rng, key);
notesInBar.push({ note: note, duration: r });
}
barsArr.push(notesInBar);
}
const sheetText = renderSheet(barsArr, beatsPerBar, beatUnit);
document.getElementById('sheet').textContent = sheetText;
});
</script>
</body>
</html>
How to use
Select number of bars you want.
Set time signature beats per bar (e.g. 3 for 3/4) and beat unit (4 for quarter note, 8 for eighth notes).
Choose a key signature (currently supports C, G, F major).
Optional: add a seed string to get repeatable output.
Click Generate and the random sheet music will appear textually below.
Notes and improvements
This is a textual, symbolic representation of sheet music. For real music notation, a library like VexFlow would be better.
Rhythms generated are simplified and do not include rests or tuplets.
Notes are chosen randomly in the scale, without melodic logic (like stepwise movement).
Unicode musical symbols may not render on all systems.
You can extend with octave changes, rests, accidentals beyond key signature, dynamics, etc.
If you want, I can provide a version integrated with VexFlow for graphical rendering. Just ask!