feat: 界面交互逻辑(拖放、走带、轨道控制、快捷键)
This commit is contained in:
@@ -0,0 +1,452 @@
|
|||||||
|
/*
|
||||||
|
* app.js —— 界面逻辑
|
||||||
|
* ------------------------------------------------------------------
|
||||||
|
* 把四个模块粘合起来:
|
||||||
|
* MidiParser(解析) → MidiPlayer(调度) → MidiSynth(发声) → MidiVisual(可视化)
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
var $ = function (id) { return document.getElementById(id); };
|
||||||
|
|
||||||
|
var els = {};
|
||||||
|
var ctx = null, synth = null, player = null, roll = null;
|
||||||
|
var song = null, title = '';
|
||||||
|
var audibleFn = null;
|
||||||
|
var scrubbing = false, resumeAfterScrub = false;
|
||||||
|
var toastTimer = null;
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', boot);
|
||||||
|
|
||||||
|
/* ============================== 启动 ============================== */
|
||||||
|
|
||||||
|
function boot() {
|
||||||
|
els = {
|
||||||
|
fileInput: $('file-input'),
|
||||||
|
dropzone: $('dropzone'),
|
||||||
|
btnOpen: $('btn-open'),
|
||||||
|
btnBrowse: $('btn-browse'),
|
||||||
|
btnDemo: $('btn-demo'),
|
||||||
|
btnDemo2: $('btn-demo2'),
|
||||||
|
canvas: $('roll'),
|
||||||
|
badgeTitle: $('badge-title'),
|
||||||
|
badgeMeta: $('badge-meta'),
|
||||||
|
btnStop: $('btn-stop'),
|
||||||
|
btnPlay: $('btn-play'),
|
||||||
|
timeCur: $('time-cur'),
|
||||||
|
timeTotal: $('time-total'),
|
||||||
|
seek: $('seek'),
|
||||||
|
speed: $('speed'),
|
||||||
|
speedVal: $('speed-val'),
|
||||||
|
volume: $('volume'),
|
||||||
|
meter: $('meter'),
|
||||||
|
infoList: $('info-list'),
|
||||||
|
trackList: $('track-list'),
|
||||||
|
toast: $('toast')
|
||||||
|
};
|
||||||
|
|
||||||
|
roll = new MidiVisual.PianoRoll(els.canvas);
|
||||||
|
|
||||||
|
initAudio();
|
||||||
|
bindEvents();
|
||||||
|
|
||||||
|
els.timeTotal.textContent = fmt(0);
|
||||||
|
els.timeCur.textContent = fmt(0);
|
||||||
|
requestAnimationFrame(loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
function initAudio() {
|
||||||
|
var AC = window.AudioContext || window.webkitAudioContext;
|
||||||
|
if (!AC) {
|
||||||
|
toast('当前浏览器不支持 Web Audio API,无法播放', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
ctx = new AC();
|
||||||
|
} catch (e) {
|
||||||
|
toast('音频初始化失败:' + e.message, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
synth = new MidiSynth.Synth(ctx, { volume: Number(els.volume.value) / 100 });
|
||||||
|
player = new MidiPlayer.Player(ctx, synth);
|
||||||
|
player.onStateChange = function (p) { setPlayIcon(p); };
|
||||||
|
player.onEnded = function () { setPlayIcon(false); };
|
||||||
|
audibleFn = function (i) { return player.isTrackAudible(i); };
|
||||||
|
}
|
||||||
|
|
||||||
|
function resumeAudio() {
|
||||||
|
if (ctx && ctx.state === 'suspended') ctx.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== 事件 ============================== */
|
||||||
|
|
||||||
|
function bindEvents() {
|
||||||
|
els.btnOpen.addEventListener('click', openPicker);
|
||||||
|
els.btnBrowse.addEventListener('click', openPicker);
|
||||||
|
els.btnDemo.addEventListener('click', loadDemo);
|
||||||
|
els.btnDemo2.addEventListener('click', loadDemo);
|
||||||
|
|
||||||
|
els.fileInput.addEventListener('change', function () {
|
||||||
|
handleFiles(els.fileInput.files);
|
||||||
|
els.fileInput.value = ''; // 允许重复选择同一个文件
|
||||||
|
});
|
||||||
|
|
||||||
|
els.btnPlay.addEventListener('click', togglePlay);
|
||||||
|
els.btnStop.addEventListener('click', stopPlayback);
|
||||||
|
|
||||||
|
/* --- 进度条:拖动时先暂停,松手后再续播,避免拖拽产生噪音 --- */
|
||||||
|
els.seek.addEventListener('pointerdown', function () {
|
||||||
|
if (!player || !song) return;
|
||||||
|
scrubbing = true;
|
||||||
|
resumeAfterScrub = player.playing;
|
||||||
|
player.pause();
|
||||||
|
});
|
||||||
|
els.seek.addEventListener('input', function () {
|
||||||
|
if (!player || !song) return;
|
||||||
|
var dur = player.duration || 1;
|
||||||
|
var t = Number(els.seek.value) / 1000 * dur;
|
||||||
|
player.seek(t);
|
||||||
|
els.timeCur.textContent = fmt(t);
|
||||||
|
});
|
||||||
|
window.addEventListener('pointerup', function () {
|
||||||
|
if (!scrubbing) return;
|
||||||
|
scrubbing = false;
|
||||||
|
if (resumeAfterScrub) { resumeAudio(); player.play(); }
|
||||||
|
resumeAfterScrub = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
/* --- 变速 --- */
|
||||||
|
els.speed.addEventListener('input', function () {
|
||||||
|
var rate = Number(els.speed.value) / 100;
|
||||||
|
els.speedVal.textContent = rate.toFixed(2) + '×';
|
||||||
|
if (player) player.setSpeed(rate);
|
||||||
|
});
|
||||||
|
|
||||||
|
/* --- 总音量 --- */
|
||||||
|
els.volume.addEventListener('input', function () {
|
||||||
|
if (player) player.setMasterVolume(Number(els.volume.value) / 100);
|
||||||
|
});
|
||||||
|
|
||||||
|
/* --- 全局拖放 --- */
|
||||||
|
['dragenter', 'dragover'].forEach(function (ev) {
|
||||||
|
window.addEventListener(ev, function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
document.body.classList.add('dragging');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
window.addEventListener('dragleave', function () {
|
||||||
|
document.body.classList.remove('dragging');
|
||||||
|
});
|
||||||
|
window.addEventListener('drop', function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
document.body.classList.remove('dragging');
|
||||||
|
if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) {
|
||||||
|
handleFiles(e.dataTransfer.files);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/* --- 快捷键 --- */
|
||||||
|
document.addEventListener('keydown', function (e) {
|
||||||
|
if (!player) return;
|
||||||
|
var tag = e.target && e.target.tagName ? e.target.tagName.toLowerCase() : '';
|
||||||
|
var isRange = tag === 'input' && e.target.type === 'range';
|
||||||
|
|
||||||
|
if (e.code === 'Space' || e.key === ' ') {
|
||||||
|
e.preventDefault();
|
||||||
|
togglePlay();
|
||||||
|
} else if (e.key === 'ArrowLeft' && !isRange) {
|
||||||
|
e.preventDefault();
|
||||||
|
player.seek(player.position - 5);
|
||||||
|
} else if (e.key === 'ArrowRight' && !isRange) {
|
||||||
|
e.preventDefault();
|
||||||
|
player.seek(player.position + 5);
|
||||||
|
} else if (e.key === 'ArrowUp') {
|
||||||
|
e.preventDefault();
|
||||||
|
nudgeVolume(4);
|
||||||
|
} else if (e.key === 'ArrowDown') {
|
||||||
|
e.preventDefault();
|
||||||
|
nudgeVolume(-4);
|
||||||
|
} else if (e.key === 'Home') {
|
||||||
|
e.preventDefault();
|
||||||
|
stopPlayback();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('resize', function () { roll.resize(); });
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPicker() {
|
||||||
|
resumeAudio();
|
||||||
|
els.fileInput.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
function nudgeVolume(delta) {
|
||||||
|
var v = Math.max(0, Math.min(120, Number(els.volume.value) + delta));
|
||||||
|
els.volume.value = String(v);
|
||||||
|
if (player) player.setMasterVolume(v / 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================ 载入流程 ============================ */
|
||||||
|
|
||||||
|
function handleFiles(files) {
|
||||||
|
if (!files || !files.length) return;
|
||||||
|
var file = files[0];
|
||||||
|
if (!/\.(mid|midi)$/i.test(file.name)) {
|
||||||
|
toast('请选择 .mid 或 .midi 文件', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
readFile(file).then(function (buf) {
|
||||||
|
loadArrayBuffer(buf, file.name);
|
||||||
|
})['catch'](function (err) {
|
||||||
|
toast('读取文件失败:' + (err && err.message ? err.message : err), true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function readFile(file) {
|
||||||
|
return new Promise(function (resolve, reject) {
|
||||||
|
if (typeof file.arrayBuffer === 'function') {
|
||||||
|
file.arrayBuffer().then(resolve, reject);
|
||||||
|
} else {
|
||||||
|
var fr = new FileReader();
|
||||||
|
fr.onload = function () { resolve(fr.result); };
|
||||||
|
fr.onerror = function () { reject(new Error('FileReader 出错')); };
|
||||||
|
fr.readAsArrayBuffer(file);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadDemo() {
|
||||||
|
resumeAudio();
|
||||||
|
try {
|
||||||
|
loadArrayBuffer(DemoSong.createDemoArrayBuffer(), '欢乐颂主题.mid');
|
||||||
|
} catch (e) {
|
||||||
|
toast('示例曲目生成失败:' + e.message, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadArrayBuffer(buffer, name) {
|
||||||
|
if (!player) { toast('音频系统不可用,无法载入', true); return; }
|
||||||
|
|
||||||
|
var parsed;
|
||||||
|
try {
|
||||||
|
parsed = MidiParser.parse(buffer);
|
||||||
|
} catch (e) {
|
||||||
|
toast('解析失败:' + e.message, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
song = parsed;
|
||||||
|
title = MidiParser.guessTitle(parsed) || stripExt(name) || '未命名曲目';
|
||||||
|
|
||||||
|
player.load(parsed);
|
||||||
|
roll.setSong(parsed);
|
||||||
|
els.dropzone.classList.add('compact');
|
||||||
|
setPlayIcon(false);
|
||||||
|
|
||||||
|
renderBadge();
|
||||||
|
renderInfo();
|
||||||
|
renderTracks();
|
||||||
|
syncTransport();
|
||||||
|
|
||||||
|
toast('已载入《' + title + '》 · ' + parsed.notes.length + ' 个音符 · ' +
|
||||||
|
fmt(parsed.duration) + ' · 点击 ▶ 播放');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== 渲染 ============================== */
|
||||||
|
|
||||||
|
function renderBadge() {
|
||||||
|
els.badgeTitle.textContent = title;
|
||||||
|
els.badgeMeta.textContent = ' · ' + song.tracks.length + ' 轨 · ' +
|
||||||
|
song.notes.length + ' 音符 · ' + bpmText(song.bpm);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderInfo() {
|
||||||
|
var tempoText;
|
||||||
|
if (song.tempos.length > 1) {
|
||||||
|
tempoText = song.tempos.length + ' 段变速(' + bpmText(song.tempos[0].bpm) +
|
||||||
|
' → ' + bpmText(song.tempos[song.tempos.length - 1].bpm) + ')';
|
||||||
|
} else {
|
||||||
|
tempoText = bpmText(song.bpm);
|
||||||
|
}
|
||||||
|
|
||||||
|
var channelText = song.channels.length
|
||||||
|
? song.channels.map(function (c) { return c === 9 ? '10(鼓)' : String(c + 1); }).join(', ')
|
||||||
|
: '—';
|
||||||
|
|
||||||
|
var rows = [
|
||||||
|
['标题', title],
|
||||||
|
['文件格式', 'SMF format ' + song.format],
|
||||||
|
['时间分辨率', song.smpte
|
||||||
|
? (song.smpte.fps + ' fps × ' + song.smpte.ticksPerFrame + ' tick')
|
||||||
|
: (song.ticksPerBeat + ' tick / 四分音符')],
|
||||||
|
['时长', fmt(song.duration)],
|
||||||
|
['音符总数', String(song.notes.length)],
|
||||||
|
['轨道数', song.tracks.length + (song.declaredTracks !== song.tracks.length
|
||||||
|
? '(文件声明 ' + song.declaredTracks + ')' : '')],
|
||||||
|
['音域', MidiParser.noteName(song.minNote) + ' → ' + MidiParser.noteName(song.maxNote)],
|
||||||
|
['使用通道', channelText],
|
||||||
|
['速度', tempoText]
|
||||||
|
];
|
||||||
|
|
||||||
|
var html = '';
|
||||||
|
rows.forEach(function (r) {
|
||||||
|
html += '<div class="row"><dt>' + escapeHtml(r[0]) + '</dt><dd>' +
|
||||||
|
escapeHtml(r[1]) + '</dd></div>';
|
||||||
|
});
|
||||||
|
els.infoList.innerHTML = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTracks() {
|
||||||
|
els.trackList.innerHTML = '';
|
||||||
|
|
||||||
|
song.tracks.forEach(function (t, i) {
|
||||||
|
var color = MidiVisual.PALETTE[i % MidiVisual.PALETTE.length];
|
||||||
|
|
||||||
|
var row = document.createElement('div');
|
||||||
|
row.className = 'track';
|
||||||
|
row.dataset.index = String(i);
|
||||||
|
|
||||||
|
var dot = document.createElement('span');
|
||||||
|
dot.className = 'dot';
|
||||||
|
dot.style.background = color;
|
||||||
|
dot.style.color = color;
|
||||||
|
|
||||||
|
var nameEl = document.createElement('span');
|
||||||
|
nameEl.className = 'tname';
|
||||||
|
nameEl.textContent = t.name || ('轨道 ' + (i + 1));
|
||||||
|
nameEl.title = nameEl.textContent;
|
||||||
|
|
||||||
|
var countEl = document.createElement('span');
|
||||||
|
countEl.className = 'tcount';
|
||||||
|
countEl.textContent = t.noteCount + ' 音符';
|
||||||
|
|
||||||
|
var mBtn = document.createElement('button');
|
||||||
|
mBtn.className = 'tbtn';
|
||||||
|
mBtn.textContent = 'M';
|
||||||
|
mBtn.title = '静音';
|
||||||
|
mBtn.addEventListener('click', function () {
|
||||||
|
player.setTrackMuted(i, !player.muted[i]);
|
||||||
|
refreshTrackStates();
|
||||||
|
});
|
||||||
|
|
||||||
|
var sBtn = document.createElement('button');
|
||||||
|
sBtn.className = 'tbtn';
|
||||||
|
sBtn.textContent = 'S';
|
||||||
|
sBtn.title = '独奏';
|
||||||
|
sBtn.addEventListener('click', function () {
|
||||||
|
player.setSolo(player.solo === i ? null : i);
|
||||||
|
refreshTrackStates();
|
||||||
|
});
|
||||||
|
|
||||||
|
row.appendChild(dot);
|
||||||
|
row.appendChild(nameEl);
|
||||||
|
row.appendChild(countEl);
|
||||||
|
row.appendChild(mBtn);
|
||||||
|
row.appendChild(sBtn);
|
||||||
|
els.trackList.appendChild(row);
|
||||||
|
});
|
||||||
|
|
||||||
|
refreshTrackStates();
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshTrackStates() {
|
||||||
|
var rows = els.trackList.querySelectorAll('.track');
|
||||||
|
Array.prototype.forEach.call(rows, function (row) {
|
||||||
|
var i = Number(row.dataset.index);
|
||||||
|
if (isNaN(i)) return;
|
||||||
|
var muted = !!player.muted[i];
|
||||||
|
var soloed = player.solo === i;
|
||||||
|
var hidden = muted || (player.solo !== null && !soloed);
|
||||||
|
|
||||||
|
row.classList.toggle('muted', hidden);
|
||||||
|
row.classList.toggle('soloed', soloed);
|
||||||
|
|
||||||
|
var btns = row.querySelectorAll('.tbtn');
|
||||||
|
if (btns.length === 2) {
|
||||||
|
btns[0].classList.toggle('on-m', muted);
|
||||||
|
btns[1].classList.toggle('on-s', soloed);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncTransport() {
|
||||||
|
els.timeTotal.textContent = fmt(song ? song.duration : 0);
|
||||||
|
els.timeCur.textContent = fmt(0);
|
||||||
|
els.seek.value = '0';
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== 走带 ============================== */
|
||||||
|
|
||||||
|
function togglePlay() {
|
||||||
|
if (!song) { toast('请先载入一个 MIDI 文件'); return; }
|
||||||
|
resumeAudio();
|
||||||
|
player.toggle();
|
||||||
|
setPlayIcon(player.playing);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopPlayback() {
|
||||||
|
if (!player) return;
|
||||||
|
player.stop();
|
||||||
|
setPlayIcon(false);
|
||||||
|
els.seek.value = '0';
|
||||||
|
els.timeCur.textContent = fmt(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPlayIcon(playing) {
|
||||||
|
els.btnPlay.textContent = playing ? '❚❚' : '▶';
|
||||||
|
els.btnPlay.title = playing ? '暂停(空格)' : '播放(空格)';
|
||||||
|
els.btnPlay.setAttribute('aria-label', playing ? '暂停' : '播放');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================= 主循环 ============================= */
|
||||||
|
|
||||||
|
function loop() {
|
||||||
|
requestAnimationFrame(loop);
|
||||||
|
if (!player) return;
|
||||||
|
|
||||||
|
var t = player.position;
|
||||||
|
els.timeCur.textContent = fmt(t);
|
||||||
|
|
||||||
|
if (!scrubbing) {
|
||||||
|
var dur = player.duration;
|
||||||
|
els.seek.value = dur > 0 ? String(Math.round(t / dur * 1000)) : '0';
|
||||||
|
}
|
||||||
|
|
||||||
|
roll.playing = player.playing;
|
||||||
|
roll.render(t, audibleFn);
|
||||||
|
MidiVisual.drawMeter(els.meter, synth ? synth.analyser : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================== 工具 ============================== */
|
||||||
|
|
||||||
|
function fmt(sec) {
|
||||||
|
if (!isFinite(sec) || sec < 0) sec = 0;
|
||||||
|
var m = Math.floor(sec / 60);
|
||||||
|
var s = sec - m * 60;
|
||||||
|
return m + ':' + (s < 10 ? '0' : '') + s.toFixed(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function bpmText(v) {
|
||||||
|
return (Math.round(v * 100) / 100) + ' BPM';
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripExt(name) {
|
||||||
|
return name ? String(name).replace(/\.[^.]+$/, '') : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(s) {
|
||||||
|
return String(s).replace(/[&<>"']/g, function (c) {
|
||||||
|
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function toast(msg, isError) {
|
||||||
|
els.toast.textContent = msg;
|
||||||
|
els.toast.classList.toggle('error', !!isError);
|
||||||
|
els.toast.classList.add('show');
|
||||||
|
if (toastTimer) clearTimeout(toastTimer);
|
||||||
|
toastTimer = setTimeout(function () {
|
||||||
|
els.toast.classList.remove('show');
|
||||||
|
}, isError ? 4200 : 3000);
|
||||||
|
}
|
||||||
|
})();
|
||||||
Reference in New Issue
Block a user