html css js rtttl parser chord "+" loop copy custom adsr osc filter pulse width lfo…
- User
html css js rtttl parser chord "+" loop copy custom adsr osc filter pulse width lfo flanger update settings share "#/" hash to id export wav
- Assistant
html css js rtttl parser chord "+" loop copy custom adsr osc filter pulse width lfo flanger update settings share "#/" hash to id export wav
It looks like you want to create a web-based RTTTL (Ring Tone Text Transfer Language) player/parser that includes advanced audio features such as MIDI-like chord support with "+" in RTTTL, looping, copying functionality, custom ADSR envelope, oscillators, filters, pulse width modulation, LFO, flanger effects, settings updates, sharing via URL hash, and exporting audio as WAV files.
That's a rich feature set! Below, I’ll provide you with a modular, starting point implementation in HTML/CSS/JavaScript that can be extended. It:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>RTTTL Player + Audio Effects</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 900px; margin: 2rem auto; padding: 1rem;
background: #222;
color: #eee;
}
textarea {
width: 100%;
font-family: monospace;
font-size: 14px;
height: 120px;
background: #111;
color: #eee;
padding: 0.5rem;
box-sizing: border-box;
border-radius: 6px;
border: 1px solid #444;
}
label {
display: block;
margin-top: 1rem;
}
input[type=range], input[type=number] {
width: 100%;
}
button {
margin: 0.5rem 0.25rem 0.5rem 0;
padding: 0.5rem 1rem;
font-size: 14px;
cursor: pointer;
border-radius: 4px;
border: none;
background: #444;
color: #eee;
}
button:hover {
background: #666;
}
.flex {
display: flex; flex-wrap: wrap; gap: 1rem;
}
.flex > div {
flex: 1 1 200px;
min-width: 200px;
}
.status {
margin-top: 1rem;
height: 25px;
}
small {
color: #888;
}
</style>
</head>
<body>
<h1>RTTTL Player + ADSR + Effects</h1>
<label for="rtttlInput">RTTTL String:</label>
<textarea id="rtttlInput" spellcheck="false" aria-label="RTTTL Input">
Enter RTTTL string here, supports chords with +
Example: Test:d=4,o=5,b=100:8c6,8e6+g6,8p,4c6
</textarea>
<div class="flex">
<div>
<label for="adsrAttack">ADSR Attack (sec): <span id="adsrAttackVal">0.01</span></label>
<input type="range" id="adsrAttack" min="0" max="1" step="0.005" value="0.01" />
</div>
<div>
<label for="adsrDecay">ADSR Decay (sec): <span id="adsrDecayVal">0.1</span></label>
<input type="range" id="adsrDecay" min="0" max="1" step="0.005" value="0.1" />
</div>
<div>
<label for="adsrSustain">ADSR Sustain (0-1): <span id="adsrSustainVal">0.7</span></label>
<input type="range" id="adsrSustain" min="0" max="1" step="0.01" value="0.7" />
</div>
<div>
<label for="adsrRelease">ADSR Release (sec): <span id="adsrReleaseVal">0.3</span></label>
<input type="range" id="adsrRelease" min="0" max="2" step="0.01" value="0.3" />
</div>
</div>
<div class="flex">
<div>
<label for="pulseWidth">Pulse Width (%): <span id="pulseWidthVal">50</span></label>
<input type="range" id="pulseWidth" min="1" max="99" step="1" value="50" />
</div>
<div>
<label for="lfoFrequency">LFO Frequency (Hz): <span id="lfoFrequencyVal">5</span></label>
<input type="range" id="lfoFrequency" min="0" max="20" step="0.1" value="5" />
</div>
<div>
<label for="lfoDepth">LFO Depth (%): <span id="lfoDepthVal">20</span></label>
<input type="range" id="lfoDepth" min="0" max="100" step="1" value="20" />
</div>
<div>
<label for="filterCutoff">Filter Cutoff (Hz): <span id="filterCutoffVal">1500</span></label>
<input type="range" id="filterCutoff" min="100" max="8000" step="10" value="1500" />
</div>
<div>
<label for="flangerMix">Flanger Mix (%): <span id="flangerMixVal">20</span></label>
<input type="range" id="flangerMix" min="0" max="100" step="1" value="20" />
</div>
</div>
<div>
<button id="playBtn">Play</button>
<button id="stopBtn">Stop</button>
<label><input type="checkbox" id="loopCheck" /> Loop</label>
<button id="copyBtn">Copy RTTTL</button>
<button id="copyShareBtn" title="Copy shareable URL">Copy Share URL</button>
<button id="exportWavBtn">Export WAV</button>
</div>
<div class="status" id="status"></div>
<script>
(() => {
"use strict";
// ########################
// RTTTL parsing + chord "+" support
// Parses format: name:d=4,o=5,b=140:8c6,8e6+g6,4p,...
// octave: 0-8, notes: c,d,e,f,g,a,b,p
// chord "+" = play notes simultaneously
//----------------------------
/** Parse RTTTL into structured array of {notes: [noteInfo], duration} objects
* notes: Each noteInfo: {freq, name, octave, isPause}
*/
function parseRTTTL(rtttl) {
// Trim and split by ":"
let parts = rtttl.trim().split(":");
if(parts.length !== 3){
throw new Error("Invalid RTTTL string (must have 3 parts separated by colons)");
}
const [name, defaultsStr, melodyStr] = parts;
// Parse defaults: d (default duration), o (default octave), b (bpm)
// defaults: d=4,o=5,b=140
let defaults = { d: 4, o: 6, b: 63 };
defaultsStr.split(",").forEach(def => {
let [k,v] = def.split("=");
if(!k || !v) return;
k = k.trim().toLowerCase();
v = v.trim();
if(k === "d") defaults.d = parseInt(v);
else if(k === "o") defaults.o = parseInt(v);
else if(k === "b") defaults.b = parseInt(v);
});
// RTTTL notes durations are relative to bpm
// duration note length in seconds = (60 / bpm) * 4 / duration
// MIDI note frequencies for octave 4 (A4=440Hz)
// RTTTL scales by octave number (0-8)
const NOTE_FREQUENCIES = {
"c": 16.35,
"c#": 17.32,
"d": 18.35,
"d#": 19.45,
"e": 20.60,
"f": 21.83,
"f#": 23.12,
"g": 24.50,
"g#": 25.96,
"a": 27.50,
"a#": 29.14,
"b": 30.87,
"p": 0 // pause
};
const semitoneMap = ["c","c#","d","d#","e","f","f#","g","g#","a","a#","b"];
// Compute frequency for note + octave
function freq(noteName, octave){
noteName = noteName.toLowerCase();
if(noteName === 'p') return 0;
let baseFreq = NOTE_FREQUENCIES[noteName];
if(!baseFreq) {
// try sharp or normal variants
if(noteName.length > 1 && noteName[1] === '#'){
let base = noteName[0];
baseFreq = NOTE_FREQUENCIES[base+"#"];
}
else return 0;
}
return baseFreq * Math.pow(2, octave);
}
// Melody parsing: notes split by ","
// Note format: [duration][note][octave][.], e.g. 16c6., 8g#, 4p
// For chords: notes separated by '+' in one note entry, e.g. 8e6+g6
function parseNote(noteStr){
// Extract duration (digits) until letter
let rest = noteStr.trim();
let durationMatch = rest.match(/^\d+/);
let duration = durationMatch ? parseInt(durationMatch[0]) : defaults.d;
rest = rest.slice(durationMatch ? durationMatch[0].length : 0);
// Note or chord
// For chord: split by '+', e.g. e6+g6
let chordParts = rest.split("+");
let notesInfo = chordParts.map(singleNoteStr => {
// singleNoteStr like c6, d#, p, f#5 etc.
// extract note name with optional sharp #
let noteNameMatch = singleNoteStr.match(/^[a-gp](#?)/i);
if(!noteNameMatch) throw new Error("Invalid note in RTTTL: " + singleNoteStr);
let noteName = noteNameMatch[0].toLowerCase();
// octave number (0-8), if present
let octaveMatch = singleNoteStr.match(/[0-8]/);
let octave = octaveMatch ? parseInt(octaveMatch[0]) : defaults.o;
// dotted note (lengthened by 1.5)
let dotted = singleNoteStr.includes(".");
return {
name: noteName,
octave,
freq: freq(noteName, octave),
isPause: (noteName === 'p'),
dotted,
};
});
return {duration, notes: notesInfo};
}
// parse melodyStr (split by ,)
const rawNotes = melodyStr.split(",");
// parse all notes
let parsedNotes = rawNotes.map(n => {
let noteObj = parseNote(n);
// duration seconds = (60 / bpm) * 4 / duration
let baseDuration = (60 / defaults.b) * 4 / noteObj.duration;
if(noteObj.notes.some(n=>n.dotted)) {
// apply dotted timing extension 1.5 times
// if any note dotted, extend duration
noteObj.notes.forEach(n=>{ if(n.dotted) n.dotted = true; });
baseDuration *= 1.5;
}
return {
notes: noteObj.notes,
durationSec: baseDuration
};
});
// Return structured song object
return {
name,
defaults,
sequence: parsedNotes
};
}
// ###########################
// Web Audio Playback engine
// Includes:
// - custom oscillator with pulse width
// - ADSR envelope
// - filter
// - LFO modulating pulse width
// - flanger effect
//----------------------------
// Pulse Oscillator — implements custom pulse with adjustable width
// Wraps Web Audio OscillatorNode or uses ScriptProcessor for pulse wave
// Using AudioWorklet would be better but not universally supported,
// So we'll build using Oscillator with periodicWave synthesis of pulse wave
// Small helper to create pulse wave PeriodicWave
function createPulseWave(audioCtx, pulseWidthPercent = 50) {
// pulseWidthPercent: 0-100
// For pulse wave Fourier series (odd harmonics)
// The amplitude of nth harmonic is proportional to sin(pi * n * duty)/ (n pi)
// where duty = pulseWidth between 0 and 1
let duty = pulseWidthPercent / 100;
const MAX_HARMONICS = 50;
let real = new Float32Array(MAX_HARMONICS +1);
let imag = new Float32Array(MAX_HARMONICS +1);
real[0] = 0;
imag[0] = 0;
for(let n=1; n<=MAX_HARMONICS; n++) {
let amplitude = (2/ (n * Math.PI)) * Math.sin(n * Math.PI * duty);
imag[n] = amplitude;
}
return audioCtx.createPeriodicWave(real, imag);
}
// Flanger node using DelayNode + OscillatorNode lowfreq modulation
// Returns: {input, output, setParams}
function createFlangerNode(audioCtx, options = {}) {
const delay = audioCtx.createDelay();
delay.delayTime.value = 0.005; // base delay
const lfo = audioCtx.createOscillator();
lfo.type = 'sine';
lfo.frequency.value = options.frequency || 0.25;
const lfoGain = audioCtx.createGain();
lfoGain.gain.value = options.depth || 0.003; // modulation depth in sec
lfo.connect(lfoGain).connect(delay.delayTime);
lfo.start();
const input = audioCtx.createGain();
const wetGain = audioCtx.createGain();
const dryGain = audioCtx.createGain();
wetGain.gain.value = options.mix || 0.3;
dryGain.gain.value = 1 - wetGain.gain.value;
input.connect(dryGain);
input.connect(delay);
delay.connect(wetGain);
const output = audioCtx.createGain();
dryGain.connect(output);
wetGain.connect(output);
return {
input,
output,
setParams(opts) {
if(opts.frequency !== undefined) lfo.frequency.value = opts.frequency;
if(opts.depth !== undefined) lfoGain.gain.value = opts.depth;
if(opts.mix !== undefined) {
wetGain.gain.value = opts.mix;
dryGain.gain.value = 1 - opts.mix;
}
}
};
}
// Player class to schedule and play RTTTL sequence
class RTTTLPlayer {
constructor(audioCtx) {
this.audioCtx = audioCtx;
this.sequence = [];
this.isPlaying = false;
this.currentNoteIndex = 0;
this.nextNoteTime = 0;
this.loop = false;
this.timeoutId = null;
this.adsr = {attack:0.01, decay: 0.1, sustain: 0.7, release: 0.3};
this.pulseWidth = 0.5;
this.lfoFrequency = 5;
this.lfoDepth = 0.2;
this.filterCutoff = 1500;
this.flangerMix = 0.2;
this.volume = 0.2;
// Create master nodes
this.masterGain = this.audioCtx.createGain();
this.masterGain.gain.value = this.volume;
this.filter = this.audioCtx.createBiquadFilter();
this.filter.type = "lowpass";
this.filter.frequency.value = this.filterCutoff;
this.flanger = createFlangerNode(audioCtx, {
frequency: 0.25,
depth: 0.003,
mix: this.flangerMix
});
this.masterGain.connect(this.filter);
this.filter.connect(this.flanger.input);
this.flanger.output.connect(this.audioCtx.destination);
}
setSequence(sequence){
this.sequence = sequence;
}
setLoop(loop){
this.loop = loop;
}
updateSettings(settings){
if(settings.adsr){
this.adsr = {...this.adsr, ...settings.adsr};
}
if(settings.pulseWidth !== undefined) this.pulseWidth = settings.pulseWidth;
if(settings.lfoFrequency !== undefined) this.lfoFrequency = settings.lfoFrequency;
if(settings.lfoDepth !== undefined) this.lfoDepth = settings.lfoDepth;
if(settings.filterCutoff !== undefined) {
this.filterCutoff = settings.filterCutoff;
this.filter.frequency.setTargetAtTime(this.filterCutoff, this.audioCtx.currentTime, 0.01);
}
if(settings.flangerMix !== undefined){
this.flangerMix = settings.flangerMix;
this.flanger.setParams({mix:this.flangerMix});
}
}
stop(){
this.isPlaying = false;
clearTimeout(this.timeoutId);
}
_playNoteAtTime(notes, duration, startTime){
// notes: array of noteInfos to play simultaneously (for chords)
// If note freq=0 => pause (skip play)
let ctx = this.audioCtx;
for(let note of notes){
if(note.isPause) {
// do nothing for pauses
continue;
}
let osc = ctx.createOscillator();
osc.type = "custom";
osc.frequency.setValueAtTime(note.freq, startTime);
let pwWave = createPulseWave(ctx, this.pulseWidth*100);
osc.setPeriodicWave(pwWave);
// LFO modulating pulse width by resynthesizing new pulses is expensive,
// so we approximate LFO by modulating oscillator detune with tiny amount,
// or simulate by modulating duty slightly via changing waveform in intervals
// (for robust implementation you'd use AudioWorklets)
// We'll modulate detune a bit for effect:
let lfoOsc = ctx.createOscillator();
lfoOsc.type = "sine";
lfoOsc.frequency.value = this.lfoFrequency;
let lfoGain = ctx.createGain();
lfoGain.gain.value = this.lfoDepth * 50; // cents
lfoOsc.connect(lfoGain);
lfoGain.connect(osc.detune);
lfoOsc.start(startTime);
lfoOsc.stop(startTime + duration);
// ADSR envelope with GainNode
let gainNode = ctx.createGain();
gainNode.gain.setValueAtTime(0, startTime);
gainNode.gain.linearRampToValueAtTime(1, startTime + this.adsr.attack);
gainNode.gain.linearRampToValueAtTime(this.adsr.sustain, startTime + this.adsr.attack + this.adsr.decay);
gainNode.gain.setValueAtTime(this.adsr.sustain, startTime + duration);
gainNode.gain.linearRampToValueAtTime(0, startTime + duration + this.adsr.release);
osc.connect(gainNode).connect(this.masterGain);
osc.start(startTime);
osc.stop(startTime + duration + this.adsr.release);
// Cleanup nodes after stop
osc.onended = () => {
osc.disconnect();
gainNode.disconnect();
lfoGain.disconnect();
lfoOsc.disconnect();
};
}
}
play(){
if(!this.sequence.length || this.isPlaying) return;
this.isPlaying = true;
this.currentNoteIndex = 0;
this.nextNoteTime = this.audioCtx.currentTime + 0.05;
const scheduler = () => {
if(!this.isPlaying) return;
if(this.currentNoteIndex >= this.sequence.length){
if(this.loop){
this.currentNoteIndex = 0;
} else {
this.isPlaying = false;
if(onFinish) onFinish();
return;
}
}
let {notes, durationSec} = this.sequence[this.currentNoteIndex];
this._playNoteAtTime(notes, durationSec, this.nextNoteTime);
this.nextNoteTime += durationSec;
this.currentNoteIndex++;
this.timeoutId = setTimeout(scheduler, (durationSec)*1000 * 0.9);
};
scheduler();
}
}
// WAV export helper using OfflineAudioContext
async function exportToWav(sequence, settings) {
// Export song to wav by rendering in OfflineAudioContext
// Needs approx length of song
let duration = sequence.reduce((acc,n)=>acc+n.durationSec,0) + 2; // +2s for release tail
const sampleRate = 44100;
let offlineCtx = new OfflineAudioContext(1, sampleRate*duration, sampleRate);
// Recreate Player chains in offline context with same settings
// Build same chain as RTTTLPlayer but without LFO detune modulation
const masterGain = offlineCtx.createGain();
masterGain.gain.value = 0.2;
const filter = offlineCtx.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.value = settings.filterCutoff || 1500;
const flanger = createFlangerNode(offlineCtx, {
frequency: 0.25,
depth: 0.003,
mix: settings.flangerMix || 0.2
});
masterGain.connect(filter);
filter.connect(flanger.input);
flanger.output.connect(offlineCtx.destination);
function createPulseWaveOffline(pwPercent) {
let duty = pwPercent/100;
const MAX_HARM = 50;
let real = new Float32Array(MAX_HARM+1);
let imag = new Float32Array(MAX_HARM+1);
real[0] = 0;
imag[0] = 0;
for(let n=1; n<=MAX_HARM; n++) {
imag[n] = (2/(n*Math.PI))*Math.sin(n*Math.PI*duty);
}
return offlineCtx.createPeriodicWave(real, imag);
}
// schedule notes
let time = 0;
for(let {notes, durationSec} of sequence){
for(let note of notes){
if(note.isPause) continue;
let osc = offlineCtx.createOscillator();
osc.type = "custom";
osc.frequency.setValueAtTime(note.freq, time);
let pwWave = createPulseWaveOffline(settings.pulseWidth*100);
osc.setPeriodicWave(pwWave);
// ADSR envelope gain
let gainNode = offlineCtx.createGain();
gainNode.gain.setValueAtTime(0, time);
gainNode.gain.linearRampToValueAtTime(1, time + settings.adsr.attack);
gainNode.gain.linearRampToValueAtTime(settings.adsr.sustain, time + settings.adsr.attack + settings.adsr.decay);
gainNode.gain.setValueAtTime(settings.adsr.sustain, time + durationSec);
gainNode.gain.linearRampToValueAtTime(0, time + durationSec + settings.adsr.release);
osc.connect(gainNode).connect(masterGain);
osc.start(time);
osc.stop(time + durationSec + settings.adsr.release);
}
time += durationSec;
}
let renderedBuffer = await offlineCtx.startRendering();
// Convert buffer to WAV Blob
let wavBlob = bufferToWavBlob(renderedBuffer);
return wavBlob;
}
// WAV encode helper (16bit PCM)
function bufferToWavBlob(buffer) {
let numChannels = buffer.numberOfChannels;
let sampleRate = buffer.sampleRate;
let length = buffer.length * numChannels * 2 + 44;
let bufferArray = new ArrayBuffer(length);
let view = new DataView(bufferArray);
function writeString(view, offset, string) {
for(let i=0; i<string.length; i++){
view.setUint8(offset+i, string.charCodeAt(i));
}
}
let offset = 0;
// RIFF chunk descriptor
writeString(view, offset, 'RIFF'); offset +=4;
view.setUint32(offset, length -8, true); offset+=4;
writeString(view, offset, 'WAVE'); offset+=4;
// fmt subchunk
writeString(view, offset, 'fmt '); offset+=4;
view.setUint32(offset, 16, true); offset+=4;
view.setUint16(offset, 1, true); offset+=2; // PCM format
view.setUint16(offset, numChannels, true); offset+=2;
view.setUint32(offset, sampleRate, true); offset+=4;
view.setUint32(offset, sampleRate * numChannels * 2, true); offset+=4; // byte rate
view.setUint16(offset, numChannels * 2, true); offset+=2; // block align
view.setUint16(offset, 16, true); offset+=2; // bits per sample
// data subchunk
writeString(view, offset, 'data'); offset+=4;
view.setUint32(offset, length - offset - 4, true); offset+=4;
// Write interleaved samples
for(let i=0; i < buffer.length; i++){
for(let ch=0; ch<numChannels; ch++){
let sample = buffer.getChannelData(ch)[i];
sample = Math.max(-1, Math.min(1, sample));
let intSample = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;
view.setInt16(offset, intSample, true);
offset+=2;
}
}
return new Blob([bufferArray], {type: 'audio/wav'});
}
// ###########################
// UI and app logic
//----------------------------
const rtttlInput = document.getElementById("rtttlInput");
const playBtn = document.getElementById("playBtn");
const stopBtn = document.getElementById("stopBtn");
const copyBtn = document.getElementById("copyBtn");
const copyShareBtn = document.getElementById("copyShareBtn");
const exportWavBtn = document.getElementById("exportWavBtn");
const loopCheck = document.getElementById("loopCheck");
const statusText = document.getElementById("status");
const adsrAttack = document.getElementById("adsrAttack");
const adsrDecay = document.getElementById("adsrDecay");
const adsrSustain = document.getElementById("adsrSustain");
const adsrRelease = document.getElementById("adsrRelease");
const pulseWidth = document.getElementById("pulseWidth");
const lfoFrequency = document.getElementById("lfoFrequency");
const lfoDepth = document.getElementById("lfoDepth");
const filterCutoff = document.getElementById("filterCutoff");
const flangerMix = document.getElementById("flangerMix");
const adsrAttackVal = document.getElementById("adsrAttackVal");
const adsrDecayVal = document.getElementById("adsrDecayVal");
const adsrSustainVal = document.getElementById("adsrSustainVal");
const adsrReleaseVal = document.getElementById("adsrReleaseVal");
const pulseWidthVal = document.getElementById("pulseWidthVal");
const lfoFrequencyVal = document.getElementById("lfoFrequencyVal");
const lfoDepthVal = document.getElementById("lfoDepthVal");
const filterCutoffVal = document.getElementById("filterCutoffVal");
const flangerMixVal = document.getElementById("flangerMixVal");
let audioCtx = null;
let player = null;
let parsedSong = null;
function updateLabels(){
adsrAttackVal.textContent = adsrAttack.value;
adsrDecayVal.textContent = adsrDecay.value;
adsrSustainVal.textContent = adsrSustain.value;
adsrReleaseVal.textContent = adsrRelease.value;
pulseWidthVal.textContent = pulseWidth.value;
lfoFrequencyVal.textContent = lfoFrequency.value;
lfoDepthVal.textContent = lfoDepth.value;
filterCutoffVal.textContent = filterCutoff.value;
flangerMixVal.textContent = flangerMix.value;
}
function getSettings(){
return {
adsr:{
attack: parseFloat(adsrAttack.value),
decay: parseFloat(adsrDecay.value),
sustain: parseFloat(adsrSustain.value),
release: parseFloat(adsrRelease.value),
},
pulseWidth: parseFloat(pulseWidth.value)/100,
lfoFrequency: parseFloat(lfoFrequency.value),
lfoDepth: parseFloat(lfoDepth.value)/100,
filterCutoff: parseFloat(filterCutoff.value),
flangerMix: parseFloat(flangerMix.value)/100
};
}
function setControls(settings){
adsrAttack.value = settings.adsr.attack;
adsrDecay.value = settings.adsr.decay;
adsrSustain.value = settings.adsr.sustain;
adsrRelease.value = settings.adsr.release;
pulseWidth.value = settings.pulseWidth * 100;
lfoFrequency.value = settings.lfoFrequency;
lfoDepth.value = settings.lfoDepth * 100;
filterCutoff.value = settings.filterCutoff;
flangerMix.value = settings.flangerMix * 100;
updateLabels();
}
function parseAndLoad(){
try{
parsedSong = parseRTTTL(rtttlInput.value);
statusText.textContent = `Loaded song: "${parsedSong.name}" with ${parsedSong.sequence.length} notes`;
if(!audioCtx){
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if(!player){
player = new RTTTLPlayer(audioCtx);
}
player.setSequence(parsedSong.sequence);
player.setLoop(loopCheck.checked);
player.updateSettings(getSettings());
return true;
} catch(e) {
statusText.textContent = "Error: "+e.message;
return false;
}
}
function copyToClipboard(text){
navigator.clipboard.writeText(text).then(()=>{
statusText.textContent = 'Copied to clipboard';
}, ()=> {
statusText.textContent = 'Failed to copy';
});
}
// Sharing: encode RTTTL to base64 for URL hash
function updateURLHash(){
let encoded = btoa(unescape(encodeURIComponent(rtttlInput.value)));
let hashStr = "#/"+encoded;
history.replaceState(null,null,hashStr);
}
function loadFromHash(){
const hash = window.location.hash;
if(hash.startsWith("#/")){
try{
let encoded = hash.slice(2);
let decoded = decodeURIComponent(escape(atob(encoded)));
rtttlInput.value = decoded;
} catch(e) {
// ignore decoding errors
}
}
}
function init(){
loadFromHash();
if(parseAndLoad()) {
updateURLHash();
}
}
// Event listeners
rtttlInput.addEventListener("input", () => {
if(parseAndLoad()){
updateURLHash();
}
});
loopCheck.addEventListener("change", () => {
if(player) player.setLoop(loopCheck.checked);
});
playBtn.addEventListener("click", () => {
if(!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
if(!player) player = new RTTTLPlayer(audioCtx);
// Resume audio context if suspended (required by some browsers)
if(audioCtx.state === 'suspended'){
audioCtx.resume();
}
if(!parsedSong){
if(!parseAndLoad()) return;
}
player.updateSettings(getSettings());
player.setLoop(loopCheck.checked);
player.play();
statusText.textContent = "Playing...";
});
stopBtn.addEventListener("click", () => {
if(player){
player.stop();
statusText.textContent = "Stopped";
}
});
// Settings change
[adsrAttack, adsrDecay, adsrSustain, adsrRelease, pulseWidth, lfoFrequency, lfoDepth, filterCutoff, flangerMix].forEach(control=>{
control.addEventListener("input", ()=>{
updateLabels();
if(player) player.updateSettings(getSettings());
});
});
copyBtn.addEventListener("click", () => {
copyToClipboard(rtttlInput.value);
});
copyShareBtn.addEventListener("click", () => {
updateURLHash();
let url = location.origin + location.pathname + location.hash;
copyToClipboard(url);
});
exportWavBtn.addEventListener("click", async () => {
if(!parsedSong){
if(!parseAndLoad()) return;
}
exportWavBtn.disabled = true;
exportWavBtn.textContent = "Exporting...";
try {
let blob = await exportToWav(parsedSong.sequence, getSettings());
let url = URL.createObjectURL(blob);
let a = document.createElement("a");
a.href = url;
a.download = parsedSong.name + ".wav";
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
a.remove();
}, 100);
} catch(e) {
statusText.textContent = "Export error: "+e.message;
}
exportWavBtn.disabled = false;
exportWavBtn.textContent = "Export WAV";
});
init();
updateLabels();
})();
</script>
</body>
</html>
+ (e.g. 8e6+g6 plays E6 and G6 together for eighth note).If you want me to help with anything more specialized or extend this example, just ask!
Not yet included in a published release.