Files
midi-player/test/parser-test.html
T

323 lines
13 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>MIDI 解析器自检 · MIDI Player</title>
<style>
:root { --ok:#7be495; --bad:#ff8fa3; --dim:#8b98a9; }
body {
margin: 0; padding: 28px 20px 60px;
background: #0a0d12; color: #e6edf5;
font-family: "Segoe UI", system-ui, "PingFang SC", "Microsoft YaHei", sans-serif;
}
.wrap { max-width: 900px; margin: 0 auto; }
h1 { font-size: 20px; margin: 0 0 4px; }
.sub { color: var(--dim); font-size: 13px; margin: 0 0 20px; }
#summary {
padding: 14px 18px; border-radius: 12px; margin-bottom: 18px;
border: 1px solid rgba(255,255,255,.1); font-size: 15px; background: #121821;
}
#summary.pass { border-color: rgba(123,228,149,.5); }
#summary.fail { border-color: rgba(255,143,163,.5); }
.case {
display: flex; gap: 10px; align-items: flex-start;
padding: 9px 14px; border-bottom: 1px dashed rgba(255,255,255,.07);
font-size: 13.5px;
}
.case .mark { flex: 0 0 auto; font-weight: 700; }
.case.ok .mark { color: var(--ok); }
.case.bad .mark { color: var(--bad); }
.case .name { flex: 1 1 auto; }
.case .msg { color: var(--bad); font-family: ui-monospace, monospace; font-size: 12px; }
.box {
background: #121821; border: 1px solid rgba(255,255,255,.1);
border-radius: 12px; padding: 10px 4px; margin-bottom: 22px;
}
a { color: #5ad2f4; }
input[type=file] { color: var(--dim); font-size: 13px; }
pre {
background: #121821; border: 1px solid rgba(255,255,255,.1); border-radius: 12px;
padding: 14px; font-size: 12px; overflow: auto; color: #b9c6d6; max-height: 320px;
}
</style>
</head>
<body>
<div class="wrap">
<h1>MIDI 解析器自检</h1>
<p class="sub">
用手工构造的字节流 + 内存生成的示例曲目,交叉验证 <code>midi-parser.js</code> 的正确性。
<a href="../index.html">&larr; 返回播放器</a>
</p>
<div id="summary">运行中…</div>
<div class="box" id="cases"></div>
<h1 style="font-size:16px">用你自己的文件验证</h1>
<p class="sub">选择任意 .mid 文件,页面会打印解析出的结构化摘要。</p>
<input type="file" id="probe" accept=".mid,.midi" />
<pre id="probe-out">(尚未选择文件)</pre>
</div>
<script src="../js/midi-parser.js"></script>
<script src="../js/demo.js"></script>
<script>
(function () {
'use strict';
var results = [];
function test(name, fn) {
try { fn(); results.push({ name: name, ok: true }); }
catch (e) { results.push({ name: name, ok: false, msg: e.message }); }
}
function ok(cond, msg) { if (!cond) throw new Error(msg || '断言失败'); }
function eq(actual, expected, msg) {
if (actual !== expected) {
throw new Error((msg ? msg + ' — ' : '') + '期望 ' + JSON.stringify(expected) +
',实际 ' + JSON.stringify(actual));
}
}
function near(actual, expected, eps, msg) {
if (Math.abs(actual - expected) > (eps || 1e-6)) {
throw new Error((msg ? msg + ' — ' : '') + '期望 ≈' + expected + ',实际 ' + actual);
}
}
function bytes(arr) { return new Uint8Array(arr).buffer; }
/* ============ 手工构造的测试文件 ============ */
/* 最简单的 format 0 文件:division=96,一个 C4 四分音符 */
var SIMPLE = bytes([
0x4D, 0x54, 0x68, 0x64, 0, 0, 0, 6, 0, 0, 0, 1, 0, 96, // MThd
0x4D, 0x54, 0x72, 0x6B, 0, 0, 0, 12, // MTrk, len = 12
0x00, 0x90, 0x3C, 0x40, // tick 0 C4 on
0x60, 0x80, 0x3C, 0x00, // tick 96 C4 off
0x00, 0xFF, 0x2F, 0x00 // end of track
]);
/* 变速文件:120 BPM 一拍,之后 240 BPM 一拍 */
var TEMPO_TEST = bytes([
0x4D, 0x54, 0x68, 0x64, 0, 0, 0, 6, 0, 0, 0, 1, 0, 96,
0x4D, 0x54, 0x72, 0x6B, 0, 0, 0, 34, // MTrk, len = 34
0x00, 0xFF, 0x51, 0x03, 0x07, 0xA1, 0x20, // tempo = 500000 (120 BPM)
0x00, 0x90, 0x3C, 0x40, // tick 0 C4 on
0x60, 0x80, 0x3C, 0x00, // tick 96 C4 off
0x00, 0xFF, 0x51, 0x03, 0x03, 0xD0, 0x90, // tempo = 250000 (240 BPM)
0x60, 0x90, 0x3E, 0x40, // tick 192 D4 on
0x60, 0x80, 0x3E, 0x00, // tick 288 D4 off
0x00, 0xFF, 0x2F, 0x00
]);
/* 运行状态(running status)+ 力度 0 当 note-off */
var RUNNING = bytes([
0x4D, 0x54, 0x68, 0x64, 0, 0, 0, 6, 0, 0, 0, 1, 0, 96,
0x4D, 0x54, 0x72, 0x6B, 0, 0, 0, 17, // MTrk, len = 17
0x00, 0x90, 0x3C, 0x40, // tick 0 C4 on
0x0A, 0x3E, 0x40, // tick 10 D4 on(省略状态字节)
0x0A, 0x3C, 0x00, // tick 20 C4 off(力度 0)
0x0A, 0x3E, 0x00, // tick 30 D4 off
0x00, 0xFF, 0x2F, 0x00
]);
/* ================== 开始测试 ================== */
test('noteName() 音名换算', function () {
eq(MidiParser.noteName(60), 'C4');
eq(MidiParser.noteName(69), 'A4');
eq(MidiParser.noteName(21), 'A0');
eq(MidiParser.noteName(108), 'C8');
});
test('最小 format 0 文件:头块字段', function () {
var s = MidiParser.parse(SIMPLE);
eq(s.format, 0, 'format');
eq(s.ticksPerBeat, 96, 'ticksPerBeat');
eq(s.tracks.length, 1, '轨数');
eq(s.notes.length, 1, '音符数');
});
test('音符配对与 tick→秒 换算', function () {
var s = MidiParser.parse(SIMPLE);
var n = s.notes[0];
eq(n.midi, 60, '音高');
eq(n.name, 'C4', '音名');
eq(n.velocity, 64, '力度');
near(n.start, 0, 1e-9, '起点');
/* 96 tick = 1 个四分音符 = 0.5 秒 @120BPM */
near(n.duration, 0.5, 1e-6, '时长');
near(s.duration, 0.5, 1e-6, '总时长');
eq(s.notes.length, 1, '不应产生多余音符');
});
test('Tempo Map:变速后 tick→秒 正确', function () {
var s = MidiParser.parse(TEMPO_TEST);
eq(s.tempos.length, 2, '速度段数');
eq(s.tempos[0].bpm, 120, '首段 BPM');
eq(s.tempos[1].bpm, 240, '次段 BPM');
near(s.tempos[1].time, 0.5, 1e-6, '变速点所在秒数');
eq(s.notes.length, 2, '音符数');
var a = s.notes[0], b = s.notes[1];
near(a.start, 0, 1e-9, '音符1 起点');
near(a.duration, 0.5, 1e-6, '音符1 时长');
near(b.start, 0.75, 1e-6, '音符2 起点(变速后)');
near(b.duration, 0.25, 1e-6, '音符2 时长(=250000us/四分音符)');
});
test('运行状态 + 力度 0 视为 note-off', function () {
var s = MidiParser.parse(RUNNING);
eq(s.notes.length, 2, '音符数');
var c = null, d = null;
s.notes.forEach(function (n) {
if (n.midi === 60) c = n;
if (n.midi === 62) d = n;
});
ok(c && d, '两个音符都应存在');
near(c.start, 0, 1e-9, 'C4 起点');
near(c.duration, 20 / 192, 1e-6, 'C4 时长');
near(d.start, 10 / 192, 1e-6, 'D4 起点');
near(d.duration, 20 / 192, 1e-6, 'D4 时长');
});
test('内置示例曲目:结构校验', function () {
var s = MidiParser.parse(DemoSong.createDemoArrayBuffer());
eq(s.format, 1, 'format');
eq(s.ticksPerBeat, 480, 'division');
eq(s.tracks.length, 5, '轨数');
eq(s.tempos.length, 3, '速度段数(120→132→120)');
eq(s.notes.length, 175, '音符总数');
});
test('内置示例曲目:按轨道统计音符数', function () {
var s = MidiParser.parse(DemoSong.createDemoArrayBuffer());
var byTrack = [0, 0, 0, 0, 0];
s.notes.forEach(function (n) { byTrack[n.track]++; });
eq(byTrack[0], 0, 'Tempo 轨不应有音符');
eq(byTrack[1], 30, '旋律轨');
eq(byTrack[2], 28, '和弦轨');
eq(byTrack[3], 17, '贝斯轨');
eq(byTrack[4], 100, '鼓组轨');
});
test('内置示例曲目:鼓组全部落在通道 9', function () {
var s = MidiParser.parse(DemoSong.createDemoArrayBuffer());
var drums = s.notes.filter(function (n) { return n.track === 4; });
ok(drums.length === 100, '鼓音符数');
drums.forEach(function (n) {
if (n.channel !== 9) throw new Error('发现非通道 9 的鼓音符');
});
});
test('内置示例曲目:音色(program)跟随 program change', function () {
var s = MidiParser.parse(DemoSong.createDemoArrayBuffer());
var melody = s.notes.filter(function (n) { return n.track === 1; });
var bass = s.notes.filter(function (n) { return n.track === 3; });
eq(melody[0].program, 0, '旋律音色');
eq(bass[0].program, 33, '贝斯音色');
});
test('内置示例曲目:第一个旋律音(E4)时长正确', function () {
var s = MidiParser.parse(DemoSong.createDemoArrayBuffer());
var first = null;
s.notes.forEach(function (n) { if (!first && n.track === 1) first = n; });
ok(first, '应存在旋律音符');
eq(first.midi, 64, '音高 E4');
eq(first.velocity, 104, '力度');
near(first.start, 0, 1e-9, '起点');
/* (2 个八分音符 = 480 tick) - 20 tick 余量,换算成秒 */
near(first.duration, 460 / 480 * 0.5, 1e-6, '时长');
});
test('内置示例曲目:所有音符时长均为正、时间递增', function () {
var s = MidiParser.parse(DemoSong.createDemoArrayBuffer());
var prev = -1;
s.notes.forEach(function (n) {
if (!(n.duration > 0)) throw new Error('存在非正时长的音符');
if (n.start < prev - 1e-9) throw new Error('音符未按起始时间排序');
prev = n.start;
});
});
test('文本 meta 事件 → guessTitle()', function () {
var s = MidiParser.parse(DemoSong.createDemoArrayBuffer());
eq(MidiParser.guessTitle(s), '示例曲目 · 欢乐颂主题');
});
/* ================== 输出结果 ================== */
var passed = results.filter(function (r) { return r.ok; }).length;
var failed = results.length - passed;
var summary = document.getElementById('summary');
summary.className = failed ? 'fail' : 'pass';
summary.innerHTML = failed
? '❌ <strong>' + failed + '</strong> 项失败 / 共 ' + results.length + ' 项'
: '✅ 全部通过:<strong>' + passed + '</strong> / ' + results.length + ' 项断言';
var host = document.getElementById('cases');
results.forEach(function (r) {
var div = document.createElement('div');
div.className = 'case ' + (r.ok ? 'ok' : 'bad');
div.innerHTML = '<span class="mark">' + (r.ok ? '✓' : '✗') + '</span>' +
'<span class="name">' + r.name + '</span>' +
(r.ok ? '' : '<span class="msg">' + r.msg + '</span>');
host.appendChild(div);
});
/* ================== 探针:解析用户文件 ================== */
document.getElementById('probe').addEventListener('change', function () {
var out = document.getElementById('probe-out');
var file = this.files && this.files[0];
if (!file) return;
function dump(buf) {
try {
var s = MidiParser.parse(buf);
var lines = [];
lines.push('标题 : ' + (MidiParser.guessTitle(s) || '(无)'));
lines.push('格式 : SMF format ' + s.format);
lines.push('时间分辨率 : ' + s.ticksPerBeat + ' tick/四分音符');
lines.push('轨道数 : ' + s.tracks.length);
lines.push('音符总数 : ' + s.notes.length);
lines.push('时长 : ' + s.duration.toFixed(2) + ' 秒');
lines.push('音域 : ' + MidiParser.noteName(s.minNote) + ' → ' + MidiParser.noteName(s.maxNote));
lines.push('速度段 : ' + s.tempos.map(function (t) {
return t.bpm + 'BPM@' + t.time.toFixed(2) + 's';
}).join(', '));
lines.push('控制器事件 : ' + s.controllers.length + ' 条');
lines.push('标记/文本 : ' + s.markers.length + ' 条');
lines.push('');
lines.push('--- 轨道明细 ---');
s.tracks.forEach(function (t) {
lines.push('[' + t.index + '] ' + (t.name || '(未命名)') +
' 音符 ' + t.noteCount + ' 事件 ' + t.eventCount +
' 结束于 tick ' + t.endTick);
});
lines.push('');
lines.push('--- 前 10 个音符 ---');
s.notes.slice(0, 10).forEach(function (n) {
lines.push(' ' + n.name.padEnd(4) + ' 起 ' + n.start.toFixed(3) + 's' +
' 长 ' + n.duration.toFixed(3) + 's' +
' 力度 ' + n.velocity + ' 通道 ' + (n.channel + 1) +
' 音色 ' + n.program);
});
out.textContent = lines.join('\n');
} catch (e) {
out.textContent = '解析失败:' + e.message;
}
}
if (typeof file.arrayBuffer === 'function') {
file.arrayBuffer().then(dump, function (e) { out.textContent = '读取失败:' + e; });
} else {
var fr = new FileReader();
fr.onload = function () { dump(fr.result); };
fr.readAsArrayBuffer(file);
}
});
})();
</script>
</body>
</html>