Files
stemengine_old/visualizer-iframes/shared/stemengine-audio-engine.js
T
2026-04-28 17:51:01 +09:00

203 lines
6.0 KiB
JavaScript

/* StemEngine iframe-local audio engine for Muon modes. */
;(function stemengineAudioEngine() {
'use strict'
var AudioCtx = window.AudioContext || window.webkitAudioContext
var ctx = null
var analyser = null
var gain = null
var sourceNode = null
var buffer = null
var startedAt = 0
var pausedAt = 0
var isPlaying = false
var playbackRate = 1
function clampTime(value, duration) {
if (!isFinite(value)) return 0
if (!isFinite(duration) || duration <= 0) return Math.max(0, value)
return Math.max(0, Math.min(value, duration))
}
function disconnectSource() {
if (!sourceNode) return
try { sourceNode.onended = null } catch (_) {}
try { sourceNode.stop() } catch (_) {}
try { sourceNode.disconnect() } catch (_) {}
sourceNode = null
}
function initialize() {
if (ctx) return
if (!AudioCtx) throw new Error('AudioContext unavailable')
ctx = new AudioCtx({ sampleRate: 44100 })
analyser = ctx.createAnalyser()
analyser.fftSize = 512
analyser.smoothingTimeConstant = 0.8
analyser.minDecibels = -100
analyser.maxDecibels = -30
gain = ctx.createGain()
gain.gain.value = 0
// Keep Muon iframe audio silent for users, but feed full-strength signal to analyser.
// source -> analyser (reactive features)
// source -> gain(0) -> destination (muted output)
gain.connect(ctx.destination)
window.__STEMENGINE_MUON_ANALYSER__ = analyser
window.__STEMENGINE_MUON_AUDIO_CTX__ = ctx
window.__STEMENGINE_VIZ_ANALYSER__ = analyser
window.__STEMENGINE_VIZ_AUDIO_CTX__ = ctx
}
function stop() {
disconnectSource()
isPlaying = false
startedAt = 0
pausedAt = 0
}
async function loadFromUrl(url) {
initialize()
if (!url) throw new Error('missing audio URL')
stop()
var response = await fetch(url, { mode: 'cors', credentials: 'omit' })
if (!response.ok) {
throw new Error('audio fetch failed: ' + response.status)
}
var arr = await response.arrayBuffer()
buffer = await ctx.decodeAudioData(arr)
pausedAt = 0
return { duration: buffer.duration }
}
function normalizeAudioBytes(bytes) {
if (bytes instanceof ArrayBuffer) return bytes
if (ArrayBuffer.isView(bytes)) {
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
}
throw new Error('unsupported audio byte payload')
}
async function loadFromBytes(bytes) {
initialize()
stop()
var arr = normalizeAudioBytes(bytes)
buffer = await ctx.decodeAudioData(arr)
pausedAt = 0
return { duration: buffer.duration }
}
function play(opts) {
initialize()
if (!buffer || !gain) return
var options = opts || {}
if (ctx.state === 'suspended') {
ctx.resume().catch(function () {})
}
disconnectSource()
sourceNode = ctx.createBufferSource()
sourceNode.buffer = buffer
playbackRate = isFinite(Number(options.rate)) ? Math.max(0.1, Number(options.rate)) : playbackRate
sourceNode.playbackRate.value = playbackRate
sourceNode.connect(analyser)
sourceNode.connect(gain)
var offset = typeof options.time === 'number' ? options.time : pausedAt
var startOffset = clampTime(offset, buffer.duration)
startedAt = ctx.currentTime - startOffset / playbackRate
pausedAt = 0
isPlaying = true
sourceNode.onended = function () {
if (!sourceNode) return
var now = getCurrentTime()
if (buffer && now >= buffer.duration - 0.01) {
isPlaying = false
pausedAt = 0
startedAt = 0
disconnectSource()
}
}
sourceNode.start(0, startOffset)
}
function pause() {
if (!ctx || !isPlaying) return
pausedAt = clampTime(getCurrentTime(), buffer ? buffer.duration : Infinity)
isPlaying = false
disconnectSource()
}
function seek(time) {
var target = clampTime(Number(time) || 0, buffer ? buffer.duration : Infinity)
var wasPlaying = isPlaying
if (wasPlaying) {
pause()
pausedAt = target
play({ time: target, rate: playbackRate })
return
}
pausedAt = target
}
function setRate(rate) {
var next = Number(rate)
if (!isFinite(next) || next <= 0) return
playbackRate = Math.max(0.1, Math.min(next, 4))
if (sourceNode) {
sourceNode.playbackRate.value = playbackRate
}
}
function getCurrentTime() {
if (!ctx) return 0
if (!isPlaying) return pausedAt
var elapsed = (ctx.currentTime - startedAt) * playbackRate
return clampTime(elapsed, buffer ? buffer.duration : Infinity)
}
function getDuration() {
return buffer ? buffer.duration : 0
}
window.__StemEngineAudioEngine__ = {
initialize: initialize,
loadFromUrl: loadFromUrl,
loadFromBytes: loadFromBytes,
play: play,
pause: pause,
stop: stop,
seek: seek,
setRate: setRate,
isPlaying: function () { return isPlaying },
getRate: function () { return playbackRate },
getAnalyser: function () { return analyser },
getContext: function () { return ctx },
getCurrentTime: getCurrentTime,
getDuration: getDuration,
}
// D-1 fix: initialize synchronously at module load.
// The original Muon's `vizInit()` is invoked synchronously by `window.onload = vizInit()`
// (a Muon-author bug — the `()` invokes immediately, not on the load event). Inside vizInit,
// `audioAnalyzer()` reads `window.__STEMENGINE_MUON_ANALYSER__` to bind the default-mode
// analyser. If we defer initialize() until DOMContentLoaded, that binding has already
// happened against wavesurfer's silent analyser and never re-acquires.
// Initializing here ensures __STEMENGINE_MUON_ANALYSER__ is set BEFORE vizInit runs
// (we are imported before the original Muon code in index.js).
// AudioContext creation without a user gesture is allowed; it starts in 'suspended' state
// and resume() succeeds on transportPlay because allow="autoplay" inherits parent activation.
try { initialize() } catch (e) { /* baseline check covers WebGL absence; AudioContext absence is rare */ }
})()