Initial import of Rhyculator
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
728bb0c657
315 files changed
+96030
No files matched your search
@@ -0,0 +1,58 @@
|
||||
using UnityEngine;
|
||||
|
||||
// 以音訊 DSP 時鐘為準的歌曲時間(秒)
|
||||
// AudioSettings.dspTime 在手機上是以音訊 buffer 為單位跳動,
|
||||
// 這裡用 realtime 在兩次跳動之間補間,並保證時間單調遞增
|
||||
public static class SongClock
|
||||
{
|
||||
public static bool Running { get; private set; }
|
||||
|
||||
private static double dspStart;
|
||||
private static double lastDsp;
|
||||
private static double lastDspRealtime;
|
||||
private static double lastReturned;
|
||||
private static double offsetSec;
|
||||
|
||||
// 補間最多往前推 0.1 秒,避免音訊卡住時畫面跑太快
|
||||
private const double MaxExtrapolation = 0.1;
|
||||
|
||||
public const string OffsetPrefKey = "AudioOffsetMs";
|
||||
|
||||
// applyOffset = false:不套用延遲補償(校正量測時使用)
|
||||
public static void Begin(double dspStartTime, bool applyOffset = true)
|
||||
{
|
||||
dspStart = dspStartTime;
|
||||
lastDsp = AudioSettings.dspTime;
|
||||
lastDspRealtime = Time.realtimeSinceStartupAsDouble;
|
||||
lastReturned = double.MinValue;
|
||||
offsetSec = applyOffset ? PlayerPrefs.GetInt(OffsetPrefKey, 0) / 1000.0 : 0;
|
||||
Running = true;
|
||||
}
|
||||
|
||||
public static void Stop()
|
||||
{
|
||||
Running = false;
|
||||
}
|
||||
|
||||
// 目前歌曲時間;音樂開始前為負值
|
||||
public static double Now
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!Running) return 0;
|
||||
|
||||
double dsp = AudioSettings.dspTime;
|
||||
double real = Time.realtimeSinceStartupAsDouble;
|
||||
if (dsp != lastDsp)
|
||||
{
|
||||
lastDsp = dsp;
|
||||
lastDspRealtime = real;
|
||||
}
|
||||
|
||||
double t = lastDsp + System.Math.Min(real - lastDspRealtime, MaxExtrapolation) - dspStart - offsetSec;
|
||||
if (t < lastReturned) t = lastReturned;
|
||||
lastReturned = t;
|
||||
return t;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user