diff --git a/js/player.js b/js/player.js new file mode 100644 index 0000000..58aa0b1 --- /dev/null +++ b/js/player.js @@ -0,0 +1,248 @@ +/* + * player.js —— 播放调度器 + * ------------------------------------------------------------------ + * 核心是一个"预读窗口调度器"(look-ahead scheduler): + * setInterval 每 25ms 唤醒一次,把未来 200ms 内将要发生的事件 + * 全部按 Web Audio 的精确时钟提前安排好。JS 定时器抖动因此被完全 + * 隔离在音频线程之外,播放不会因为主线程卡顿而走音。 + * + * 同时负责:播放/暂停/停止/跳转/变速,轨道静音与独奏, + * 以及 CC 事件(音量、声像、表情、全部音符关闭)的下发。 + */ +(function (root, factory) { + if (typeof module === 'object' && module.exports) module.exports = factory(); + else root.MidiPlayer = factory(); +})(typeof self !== 'undefined' ? self : this, function () { + 'use strict'; + + var HANDLED_CC = { 7: 1, 10: 1, 11: 1, 64: 1, 120: 1, 123: 1 }; + var TICK_MS = 25; // 调度器唤醒周期 + var LOOKAHEAD = 0.2; // 预读窗口(秒) + var PREROLL = 0.06; // 起播前的调度余量(秒) + + function Player(ctx, synth) { + this.ctx = ctx; + this.synth = synth; + + this.song = null; + this.events = []; + this.cursor = 0; + + this.playing = false; + this.speed = 1; + this.baseSongTime = 0; // 起播(或跳转)时的歌曲时间 + this.startedAt = 0; // 对应的 AudioContext 时间 + this.timerId = null; + + this.muted = {}; // trackIndex -> true + this.solo = null; // trackIndex 或 null + + this.onPosition = null; // (seconds) => void + this.onStateChange = null; + this.onEnded = null; + } + + /* ------------------------------ 装载 ------------------------------ */ + + Player.prototype.load = function (song) { + this.stop(); + this.song = song; + this.baseSongTime = 0; + this.cursor = 0; + this.muted = {}; + this.solo = null; + + var evs = []; + var notes = song.notes || []; + for (var i = 0; i < notes.length; i++) { + var n = notes[i]; + evs.push({ time: n.start, kind: 'on', note: n }); + evs.push({ time: n.start + n.duration, kind: 'off', note: n }); + } + var ccs = song.controllers || []; + for (var j = 0; j < ccs.length; j++) { + var c = ccs[j]; + if (HANDLED_CC[c.number]) evs.push({ time: c.time, kind: 'cc', cc: c }); + } + + /* 同一时刻:先关音,再改控制器,最后开音,避免"粘连音" */ + evs.sort(function (a, b) { + if (a.time !== b.time) return a.time - b.time; + return rank(a) - rank(b); + }); + function rank(e) { + return e.kind === 'off' ? 0 : (e.kind === 'cc' ? 1 : 2); + } + + this.events = evs; + return song; + }; + + /* --------------------------- 基本信息 --------------------------- */ + + Object.defineProperty(Player.prototype, 'duration', { + get: function () { return this.song ? this.song.duration : 0; } + }); + + Object.defineProperty(Player.prototype, 'position', { + get: function () { + if (!this.song) return 0; + if (!this.playing) return Math.min(this.baseSongTime, this.duration); + var p = this.baseSongTime + (this.ctx.currentTime - this.startedAt) * this.speed; + if (p < this.baseSongTime) p = this.baseSongTime; + return Math.min(p, this.duration); + } + }); + + /* ------------------------------ 控制 ------------------------------ */ + + Player.prototype.play = function () { + if (!this.song || this.playing) return; + if (this.baseSongTime >= this.duration - 0.02) this.baseSongTime = 0; + this.startedAt = this.ctx.currentTime + PREROLL; + this.cursor = this._indexAt(this.baseSongTime); + this.playing = true; + var self = this; + this._tick(); + this.timerId = setInterval(function () { self._tick(); }, TICK_MS); + this._emit(); + }; + + Player.prototype.pause = function () { + if (!this.playing) return; + this.baseSongTime = this.position; + this.playing = false; + if (this.timerId) { clearInterval(this.timerId); this.timerId = null; } + this.synth.panic(this.ctx.currentTime); + this._emit(); + }; + + Player.prototype.toggle = function () { + if (this.playing) this.pause(); else this.play(); + }; + + Player.prototype.stop = function () { + this.playing = false; + if (this.timerId) { clearInterval(this.timerId); this.timerId = null; } + this.baseSongTime = 0; + this.cursor = 0; + if (this.synth) this.synth.panic(this.ctx.currentTime); + this._emit(); + }; + + Player.prototype.seek = function (seconds) { + var t = Math.max(0, Math.min(seconds, this.duration)); + if (this.playing) { + this._reposition(t); + } else { + this.synth.panic(this.ctx.currentTime); + this.baseSongTime = t; + this.cursor = this._indexAt(t); + this._emit(); + } + }; + + Player.prototype.setSpeed = function (rate) { + var r = Math.max(0.1, Math.min(4, rate || 1)); + if (r === this.speed) return; + var pos = this.position; + this.speed = r; + if (this.playing) this._reposition(pos); + else this.baseSongTime = pos; + }; + + Player.prototype.setTrackMuted = function (index, muted) { + if (muted) this.muted[index] = true; else delete this.muted[index]; + this._resync(); + }; + + Player.prototype.setSolo = function (index) { + this.solo = (index === null || index === undefined) ? null : index; + this._resync(); + }; + + Player.prototype.isTrackAudible = function (index) { + if (this.muted[index]) return false; + if (this.solo !== null && this.solo !== index) return false; + return true; + }; + + Player.prototype.setMasterVolume = function (v) { + this.synth.setVolume(v); + }; + + /* ---------------------------- 内部实现 ---------------------------- */ + + Player.prototype._emit = function () { + if (typeof this.onStateChange === 'function') this.onStateChange(this.playing); + }; + + /* 播放中切换静音/独奏/变速时,重新对齐时间轴并掐掉残留音 */ + Player.prototype._resync = function () { + if (!this.song) return; + if (this.playing) this._reposition(this.position); + else this.synth.panic(this.ctx.currentTime); + }; + + Player.prototype._reposition = function (t) { + var clamped = Math.max(0, Math.min(t, this.duration)); + this.synth.panic(this.ctx.currentTime); + this.baseSongTime = clamped; + this.startedAt = this.ctx.currentTime + PREROLL; + this.cursor = this._indexAt(clamped); + this._tick(); + }; + + /* 二分查找:第一个 time >= t 的事件下标 */ + Player.prototype._indexAt = function (t) { + var lo = 0, hi = this.events.length; + while (lo < hi) { + var mid = (lo + hi) >> 1; + if (this.events[mid].time < t) lo = mid + 1; else hi = mid; + } + return lo; + }; + + Player.prototype._tick = function () { + var ctx = this.ctx; + var now = ctx.currentTime; + var songNow = this.baseSongTime + (now - this.startedAt) * this.speed; + if (songNow < this.baseSongTime) songNow = this.baseSongTime; + var horizon = songNow + LOOKAHEAD * Math.max(1, this.speed); + + while (this.cursor < this.events.length && this.events[this.cursor].time <= horizon) { + var ev = this.events[this.cursor++]; + var when = this.startedAt + (ev.time - this.baseSongTime) / this.speed; + this._fire(ev, when); + } + + if (typeof this.onPosition === 'function') this.onPosition(this.position); + + if (songNow >= this.duration) { + this.playing = false; + if (this.timerId) { clearInterval(this.timerId); this.timerId = null; } + this.baseSongTime = this.duration; + this.synth.panic(now + 0.6); + if (typeof this.onEnded === 'function') this.onEnded(); + this._emit(); + } + }; + + Player.prototype._fire = function (ev, when) { + if (ev.kind === 'cc') { + var c = ev.cc; + if (!this.isTrackAudible(c.track)) return; + this.synth.handleCC(c.channel, c.number, c.value, when); + return; + } + var n = ev.note; + if (!this.isTrackAudible(n.track)) return; + if (ev.kind === 'on') { + this.synth.noteOn(n.channel, n.midi, n.velocity, when, n.program); + } else { + this.synth.noteOff(n.channel, n.midi, when); + } + }; + + return { Player: Player, HANDLED_CC: HANDLED_CC }; +});