Act as an old-school ES5 web developer. Given a function named onMIDIMessage() that runs…
- User
Act as an old-school ES5 web developer. Given a function named onMIDIMessage() that runs every time a user inputs a key on their MIDI device, create a function called playPianoNote() that plays the correct note on the piano via the web browser. Import any libraries necessary.
- Assistant
Here’s an old-school ES5 solution using the popular Soundfont-Player library to load an acoustic grand piano and play MIDI notes as they arrive.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ES5 MIDI → Piano</title> </head> <body> <h1>ES5 MIDI Piano Demo 🎹</h1> <!-- 1) Include Soundfont-Player and initialize AudioContext --> <script src="https://cdnjs.cloudflare.com/ajax/libs/soundfont-player/0.7.1/soundfont-player.min.js"></script> <script> // Cross-browser AudioContext var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext(); var pianoPlayer = null; // 2) Load the piano instrument Soundfont.instrument(audioCtx, 'acoustic_grand_piano') .then(function(player){ pianoPlayer = player; console.log('Piano loaded! 🎹'); }) .catch(function(err){ console.error('Failed to load piano:', err); }); // 3) Convert a MIDI note number to note name, e.g. 60 → "C4" function midiToNoteName(midiNumber) { var noteNames = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']; var octave = Math.floor(midiNumber / 12) - 1; var note = noteNames[midiNumber % 12]; return note + octave; } // 4) The requested playPianoNote() function function playPianoNote(midiNumber, velocity) { if (!pianoPlayer) { console.warn('Piano not yet loaded.'); return; } var noteName = midiToNoteName(midiNumber); // velocity [0–127] → gain [0–1] var gain = (velocity / 127) * 0.8 + 0.2; // play for 1 second by default pianoPlayer.play(noteName, audioCtx.currentTime, { gain: gain, duration: 1.0 }); console.log('Playing', noteName, 'vel', velocity); } // 5) Example onMIDIMessage handler // Call this on every MIDI message from your device. function onMIDIMessage(midiMessageEvent) { var data = midiMessageEvent.data; var status = data[0] & 0xF0; // high nibble = command var noteNum = data[1]; var velocity= data[2]; // 0x90 = Note On, 0x80 = Note Off if (status === 0x90 && velocity > 0) { // Note-On → play playPianoNote(noteNum, velocity); } // (Optionally handle Note-Off if you want to trigger release) } // 6) Hook up Web MIDI API (optional boilerplate) if (navigator.requestMIDIAccess) { navigator.requestMIDIAccess().then(function(midiAccess) { var inputs = midiAccess.inputs.values(); for (var input = inputs.next(); input && !input.done; input = inputs.next()) { input.value.onmidimessage = onMIDIMessage; } console.log('MIDI ready! Connect your keyboard.'); }); } else { console.warn('Web MIDI API not supported in this browser.'); } </script> </body> </html>How it works step by step:
- We import Soundfont-Player from a CDN and create a single
AudioContext. - We load the “acoustic_grand_piano” instrument.
- We convert MIDI numbers (0–127) into note names like “C4”.
playPianoNote(midiNumber, velocity)looks up the note name, maps velocity to gain, and triggers a 1s piano tone.- In your existing
onMIDIMessage()(here shown in full), we detect Note-On messages (0x90) and call our piano-play function.
Feel free to tweak duration, gain curves or swap in any other Soundfont instrument. Enjoy rocking that old-school ES5 approach! 🎶
- We import Soundfont-Player from a CDN and create a single
- User
Excellent! How can I add release damper functionality (when the key is released it damps the note)?
- Assistant
Here’s how you can hook up “note-off” (key release) events to actually stop (damp) the piano tone instead of letting it play its full 1 s duration. We’ll:
- Keep a map of currently playing notes (
activeNotes) - When
playPianoNote()is called we store the returned AudioBufferSourceNode in that map - When a Note-Off (or Note-On with velocity = 0) comes in we look up and
.stop()that node
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ES5 MIDI → Piano with Damper</title> </head> <body> <h1>ES5 MIDI Piano Demo 🎹 (with damper)</h1> <script src="https://cdnjs.cloudflare.com/ajax/libs/soundfont-player/0.7.1/soundfont-player.min.js"></script> <script> // Cross-browser AudioContext var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext(); var pianoPlayer = null; // Map midiNumber → AudioBufferSourceNode var activeNotes = {}; // 1) Load piano Soundfont.instrument(audioCtx, 'acoustic_grand_piano') .then(function(player){ pianoPlayer = player; console.log('Piano loaded!'); }) .catch(function(err){ console.error('Error loading piano:', err); }); // 2) MIDI ⇒ note name function midiToNoteName(n) { var names = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']; var octave = Math.floor(n/12) - 1; return names[n % 12] + octave; } // 3) Play on Note-On function playPianoNote(midiNumber, velocity) { if (!pianoPlayer) { console.warn('📭 Piano not yet loaded.'); return; } var noteName = midiToNoteName(midiNumber); var gain = (velocity / 127) * 0.8 + 0.2; // We deliberately give it a long duration; we'll stop it manually on key-up var src = pianoPlayer.play(noteName, audioCtx.currentTime, { gain: gain, duration: 10 // plenty of time; we'll cut it off }); // Store the source node so we can stop it on damper (Note-Off) activeNotes[midiNumber] = src; } // 4) Release (dampen) on Note-Off function releasePianoNote(midiNumber) { var src = activeNotes[midiNumber]; if (src) { try { // Stop almost immediately (you can add a small fade if you like) src.stop(audioCtx.currentTime + 0.02); } catch(e) { console.warn('Could not stop note', midiNumber, e); } delete activeNotes[midiNumber]; } } // 5) onMIDIMessage: route Note-On & Note-Off function onMIDIMessage(e) { var data = e.data, status = data[0] & 0xF0, noteNum = data[1], velocity = data[2]; // 0x90 = Note-On, 0x80 = Note-Off if (status === 0x90 && velocity > 0) { playPianoNote(noteNum, velocity); } // treat a Note-On with vel=0 as Note-Off too else if (status === 0x80 || (status === 0x90 && velocity === 0)) { releasePianoNote(noteNum); } } // 6) Wire up Web MIDI if (navigator.requestMIDIAccess) { navigator.requestMIDIAccess().then(function(midi) { var inputs = midi.inputs.values(); for (var inp = inputs.next(); inp && !inp.done; inp = inputs.next()) { inp.value.onmidimessage = onMIDIMessage; } console.log('MIDI ready. Play/Release keys to hear damper in action.'); }); } else { console.warn('Web MIDI API not supported.'); } </script> </body> </html>Explanation of the new bits:
•
activeNoteskeeps track of which AudioBufferSourceNode is playing each MIDI key.
• InplayPianoNote()we give the note a longduration(10 s), then store the returned source inactiveNotes.
• InreleasePianoNote()we retrieve that source and immediately call.stop()to silence it (the “damper” effect).
• We updatedonMIDIMessage()to firereleasePianoNote()on status 0x80 or Note-On with velocity = 0.Feel free to tweak the tiny stop-delay (
+0.02) or implement a gentle fade‐out by connecting your own GainNode if you want a smoother release envelope. Enjoy! 🎶 - Keep a map of currently playing notes (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.