Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
"""MIDI 读写测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from qbh.melody import Melody
|
||||
from qbh.midiio import read_midi, read_midi_melody, write_midi
|
||||
|
||||
|
||||
def _melody() -> Melody:
|
||||
midis = np.array([60.0, 62.0, 64.0, 67.0, 69.0])
|
||||
starts = np.array([0.0, 0.5, 1.0, 1.5, 2.0])
|
||||
durs = np.array([0.5, 0.5, 0.5, 0.5, 0.9])
|
||||
return Melody(midis, starts, durs, "roundtrip", "回环测试")
|
||||
|
||||
|
||||
def test_write_read_roundtrip(tmp_path):
|
||||
path = tmp_path / "mel.mid"
|
||||
original = _melody()
|
||||
write_midi(path, original, bpm=120.0)
|
||||
|
||||
midi = read_midi(path)
|
||||
assert midi.tracks
|
||||
melody = read_midi_melody(path)
|
||||
|
||||
assert melody.n_notes == original.n_notes
|
||||
assert np.allclose(melody.midis, original.midis)
|
||||
# 时间分辨率受 PPQ 限制,允许 1/480 拍的误差
|
||||
assert np.max(np.abs(melody.starts - original.starts)) < 0.02
|
||||
assert np.max(np.abs(melody.durs - original.durs)) < 0.02
|
||||
|
||||
|
||||
def test_bpm_is_recovered(tmp_path):
|
||||
path = tmp_path / "fast.mid"
|
||||
write_midi(path, _melody(), bpm=150.0)
|
||||
assert read_midi(path).bpm == pytest.approx(150.0, abs=0.5)
|
||||
|
||||
|
||||
def test_rejects_non_midi(tmp_path):
|
||||
path = tmp_path / "not.mid"
|
||||
path.write_bytes(b"this is not midi at all")
|
||||
with pytest.raises(ValueError):
|
||||
read_midi(path)
|
||||
|
||||
|
||||
def test_reads_project_midi_library():
|
||||
"""真实 MIDI 曲库应能全部解析出合理旋律。"""
|
||||
from pathlib import Path
|
||||
|
||||
midi_dir = Path(__file__).resolve().parent.parent / "data" / "midi"
|
||||
files = sorted(midi_dir.glob("*.mid"))
|
||||
if not files:
|
||||
pytest.skip("未找到 data/midi 曲库")
|
||||
|
||||
for path in files:
|
||||
melody = read_midi_melody(path)
|
||||
assert melody.n_notes >= 4, path.name
|
||||
assert melody.duration > 0.5, path.name
|
||||
# 单声部化之后音高应落在合理音区
|
||||
assert 30.0 < melody.median_pitch < 100.0, path.name
|
||||
|
||||
|
||||
def test_monophonize_keeps_highest_on_overlap():
|
||||
from qbh.midiio import MidiNote, _monophonize
|
||||
|
||||
notes = [
|
||||
MidiNote(60, 0.0, 1.0),
|
||||
MidiNote(67, 0.5, 1.0), # 与前者重叠且更高
|
||||
]
|
||||
reduced = _monophonize(notes)
|
||||
pitches = [n.pitch for n in reduced]
|
||||
assert 67 in pitches
|
||||
assert sum(1 for n in reduced if n.pitch == 60) <= 1
|
||||
Reference in New Issue
Block a user