Mus_Sim_1-beta / sim /tone_component.py
adisha1971's picture
Upload 9 files
7700c61 verified
Raw History Blame Contribute Delete
8.41 kB
from __future__ import annotations
__version__ = "1.5.5"
import json
import streamlit.components.v1 as components
def tone_player(
chord_midi,
instrument: str,
mode: str,
tempo_bpm: int,
sustain_s: float,
trigger_play: bool,
):
"""
v1.0.3 audio fix:
- Piano uses Salamander samples via Tone.Sampler, but waits until loaded before triggering notes.
- Includes button inside iframe for browser gesture.
- Uses a deterministic component key to force refresh when chord/instrument changes.
"""
payload = {
"midi": chord_midi,
"instrument": instrument,
"mode": mode,
"tempo": int(tempo_bpm),
"sustain": float(sustain_s),
"autoplay": bool(trigger_play),
}
payload_json = json.dumps(payload)
comp_key = f"tone_{instrument}_{mode}_{tempo_bpm}_{sustain_s}_" + "_".join(str(int(x)) for x in chord_midi)
html = """
<div style="font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial; font-size: 13px;">
<div id="status" style="opacity:0.85; margin-bottom:6px;">
Audio ready. If you don’t hear sound, click <b>Enable Audio / Play</b> below.
</div>
<button id="playBtn" style="padding:6px 10px; border-radius:10px; border:1px solid #ccc; background:#fff; cursor:pointer;">
Enable Audio / Play
</button>
<span id="loading" style="margin-left:10px; opacity:0.75;"></span>
</div>
<script src="https://unpkg.com/tone@14.8.49/build/Tone.js"></script>
<script>
const payload = __PAYLOAD_JSON__;
const statusEl = document.getElementById("status");
const loadingEl = document.getElementById("loading");
function midiToFreq(midi) {
return Tone.Frequency(midi, "midi").toFrequency();
}
function midiToNoteName(m) {
return Tone.Frequency(m, "midi").toNote();
}
const SALAMANDER_BASE = "https://tonejs.github.io/audio/salamander/";
// Cache instruments in the iframe
let currentInst = null;
let currentName = null;
let samplerLoading = false;
function createPianoSampler() {
const urls = {
"A0": "A0.mp3",
"C1": "C1.mp3",
"D#1": "Ds1.mp3",
"F#1": "Fs1.mp3",
"A1": "A1.mp3",
"C2": "C2.mp3",
"D#2": "Ds2.mp3",
"F#2": "Fs2.mp3",
"A2": "A2.mp3",
"C3": "C3.mp3",
"D#3": "Ds3.mp3",
"F#3": "Fs3.mp3",
"A3": "A3.mp3",
"C4": "C4.mp3",
"D#4": "Ds4.mp3",
"F#4": "Fs4.mp3",
"A4": "A4.mp3",
"C5": "C5.mp3",
"D#5": "Ds5.mp3",
"F#5": "Fs5.mp3",
"A5": "A5.mp3",
"C6": "C6.mp3",
"D#6": "Ds6.mp3",
"F#6": "Fs6.mp3",
"A6": "A6.mp3",
"C7": "C7.mp3",
"D#7": "Ds7.mp3",
"F#7": "Fs7.mp3",
"A7": "A7.mp3",
"C8": "C8.mp3"
};
samplerLoading = true;
if (loadingEl) loadingEl.textContent = "Loading piano samples…";
const sampler = new Tone.Sampler({
urls,
baseUrl: SALAMANDER_BASE,
onload: () => {
samplerLoading = false;
if (loadingEl) loadingEl.textContent = "";
if (statusEl) statusEl.textContent = "Piano samples loaded. Click Enable Audio / Play.";
}
}).toDestination();
return sampler;
}
function makeInstrument(name) {
if (name === "Piano") {
return createPianoSampler();
}
if (name === "Organ") {
return new Tone.PolySynth(Tone.Synth, {
oscillator: { type: "sine" },
envelope: { attack: 0.01, decay: 0.05, sustain: 0.85, release: 0.35 }
}).toDestination();
}
if (name === "Nylon Guitar") {
return new Tone.PolySynth(Tone.PluckSynth, {
attackNoise: 1,
dampening: 3000,
resonance: 0.9
}).toDestination();
}
if (name === "Choir") {
const chorus = new Tone.Chorus(4, 2.5, 0.25).toDestination();
return new Tone.PolySynth(Tone.Synth, {
oscillator: { type: "sawtooth" },
envelope: { attack: 0.12, decay: 0.2, sustain: 0.7, release: 1.4 }
}).connect(chorus);
}
return new Tone.PolySynth(Tone.Synth).toDestination();
}
function ensureInstrument() {
if (!currentInst || currentName !== payload.instrument) {
currentName = payload.instrument;
currentInst = makeInstrument(payload.instrument);
}
return currentInst;
}
function playNotes(inst) {
const now = Tone.now();
const dur = Math.max(0.15, payload.sustain);
if (payload.mode === "Arpeggio") {
const beat = 60.0 / Math.max(40, payload.tempo);
payload.midi.forEach((m, i) => {
const t = now + i * beat * 0.5;
if (payload.instrument === "Piano") {
inst.triggerAttackRelease(midiToNoteName(m), dur, t, 0.9);
} else {
inst.triggerAttackRelease(midiToFreq(m), dur, t);
}
});
} else {
payload.midi.forEach((m) => {
if (payload.instrument === "Piano") {
inst.triggerAttack(midiToNoteName(m), now, 0.9);
} else {
inst.triggerAttack(midiToFreq(m), now);
}
});
if (inst.releaseAll) inst.releaseAll(now + dur);
else payload.midi.forEach((m) => inst.triggerRelease(payload.instrument === "Piano" ? midiToNoteName(m) : midiToFreq(m), now + dur));
}
}
async function playNow() {
try {
await Tone.start();
const inst = ensureInstrument();
// If piano sampler is still loading, queue playback shortly after load.
if (payload.instrument === "Piano" && samplerLoading) {
if (statusEl) statusEl.textContent = "Loading piano samples… will play when ready.";
const timer = setInterval(() => {
if (!samplerLoading) {
clearInterval(timer);
playNotes(inst);
if (statusEl) statusEl.textContent = `Playing: ${payload.instrument} • ${payload.mode}`;
}
}, 150);
return;
}
playNotes(inst);
if (statusEl) statusEl.textContent = `Playing: ${payload.instrument} • ${payload.mode}`;
} catch (e) {
if (statusEl) statusEl.textContent = "Audio blocked by browser. Click the button again, or check site audio permissions.";
console.error(e);
}
}
document.getElementById("playBtn").addEventListener("click", playNow);
if (payload.autoplay) playNow();
</script>
"""
html = html.replace("__PAYLOAD_JSON__", payload_json)
components.html(html + f"\n<!-- {comp_key} -->", height=95)
def tone_progression_player(chords_midi: list[list[int]], bpm: int = 90, chord_beats: float = 2.0, instrument: str = "piano", play: bool = False):
"""Play a chord progression in the browser using Tone.js (additive)."""
import streamlit.components.v1 as components
import json
payload = {
"chords": chords_midi,
"bpm": int(bpm),
"chord_beats": float(chord_beats),
"instrument": instrument,
"play": bool(play),
}
html = """<div style='display:none'></div>
<script src='https://unpkg.com/tone@14.8.49/build/Tone.js'></script>
<script>
const payload = __PAYLOAD__;
function midiToFreq(m) {
return Tone.Frequency(m, "midi");
}
function makeSynth(name) {
if (name === "organ") {
return new Tone.PolySynth(Tone.Synth, { oscillator: { type: "sine" } }).toDestination();
}
if (name === "nylon_guitar") {
return new Tone.PolySynth(Tone.PluckSynth).toDestination();
}
if (name === "choir") {
return new Tone.PolySynth(Tone.AMSynth).toDestination();
}
return new Tone.PolySynth(Tone.Synth, { oscillator: { type: "triangle" } }).toDestination();
}
async function playProg() {
try {
await Tone.start(); // user gesture required
Tone.Transport.stop();
Tone.Transport.cancel();
Tone.Transport.bpm.value = payload.bpm;
const synth = makeSynth(payload.instrument);
const beatSec = 60.0 / payload.bpm;
const chordDur = payload.chord_beats * beatSec;
payload.chords.forEach((ch, idx) => {
const t = idx * chordDur;
Tone.Transport.schedule((time) => {
const freqs = ch.map(midiToFreq);
synth.triggerAttackRelease(freqs, chordDur * 0.9, time, 0.8);
}, t);
});
Tone.Transport.start("+0.05");
} catch (e) {
console.error(e);
}
}
if (payload.play) {
playProg();
}
</script>""".replace("__PAYLOAD__", json.dumps(payload))
components.html(html, height=0)