GameAudio.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public enum GameSfx
  5. {
  6. Tap,
  7. Pick,
  8. Drop,
  9. Clear,
  10. Coin,
  11. Win,
  12. Fail,
  13. Error,
  14. Buy,
  15. Spin
  16. }
  17. [DisallowMultipleComponent]
  18. public class GameAudio : MonoBehaviour
  19. {
  20. const int SampleRate = 44100;
  21. const float BgmStepDuration = 0.3f;
  22. const float MinGain = 0.0001f;
  23. static readonly float[] BgmNotes =
  24. {
  25. 523f, 659f, 784f, 659f, 587f, 698f, 880f, 698f,
  26. 523f, 659f, 784f, 1046f, 880f, 784f, 659f, 587f
  27. };
  28. enum Waveform
  29. {
  30. Sine,
  31. Square,
  32. Triangle,
  33. Sawtooth
  34. }
  35. static GameAudio instance;
  36. AudioSource musicSource;
  37. AudioSource sfxSource;
  38. AudioClip musicClip;
  39. readonly Dictionary<long, AudioClip> sfxClips = new Dictionary<long, AudioClip>();
  40. bool bgmStarted;
  41. bool interacted;
  42. public static bool BgmEnabled
  43. {
  44. get
  45. {
  46. if (!Application.isPlaying)
  47. return false;
  48. SaveService.EnsureLoaded();
  49. return SaveService.Data.settings.bgm;
  50. }
  51. }
  52. public static bool SfxEnabled
  53. {
  54. get
  55. {
  56. if (!Application.isPlaying)
  57. return false;
  58. SaveService.EnsureLoaded();
  59. return SaveService.Data.settings.sfx;
  60. }
  61. }
  62. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
  63. static void Bootstrap()
  64. {
  65. Ensure();
  66. }
  67. static GameAudio Ensure()
  68. {
  69. if (!Application.isPlaying)
  70. return null;
  71. if (instance != null)
  72. return instance;
  73. var go = new GameObject("GameAudio");
  74. DontDestroyOnLoad(go);
  75. return go.AddComponent<GameAudio>();
  76. }
  77. void Awake()
  78. {
  79. if (instance != null && instance != this)
  80. {
  81. Destroy(gameObject);
  82. return;
  83. }
  84. instance = this;
  85. DontDestroyOnLoad(gameObject);
  86. musicSource = gameObject.AddComponent<AudioSource>();
  87. musicSource.playOnAwake = false;
  88. musicSource.loop = true;
  89. musicSource.spatialBlend = 0f;
  90. musicSource.volume = 1f;
  91. sfxSource = gameObject.AddComponent<AudioSource>();
  92. sfxSource.playOnAwake = false;
  93. sfxSource.loop = false;
  94. sfxSource.spatialBlend = 0f;
  95. sfxSource.volume = 1f;
  96. }
  97. void OnDestroy()
  98. {
  99. if (instance == this)
  100. instance = null;
  101. }
  102. void Update()
  103. {
  104. if (bgmStarted || interacted)
  105. return;
  106. if (Input.anyKeyDown || Input.touchCount > 0)
  107. {
  108. interacted = true;
  109. StartBgmIfAllowed();
  110. }
  111. }
  112. public static void NotifyInteraction()
  113. {
  114. GameAudio audio = Ensure();
  115. if (audio == null)
  116. return;
  117. audio.interacted = true;
  118. audio.StartBgmIfAllowed();
  119. }
  120. public static void PlayTap()
  121. {
  122. PlaySfx(GameSfx.Tap);
  123. }
  124. public static void PlaySfx(GameSfx cue, int variant = 0)
  125. {
  126. GameAudio audio = Ensure();
  127. if (audio == null)
  128. return;
  129. audio.interacted = true;
  130. audio.StartBgmIfAllowed();
  131. if (!SfxEnabled)
  132. return;
  133. AudioClip clip = audio.GetSfxClip(cue, variant);
  134. if (clip != null)
  135. audio.sfxSource.PlayOneShot(clip);
  136. }
  137. public static void StopBgmImmediate()
  138. {
  139. if (instance == null)
  140. return;
  141. instance.StopBgm();
  142. }
  143. public static void RefreshSettings()
  144. {
  145. GameAudio audio = Ensure();
  146. if (audio == null)
  147. return;
  148. if (BgmEnabled)
  149. {
  150. if (audio.interacted)
  151. audio.StartBgmIfAllowed();
  152. }
  153. else
  154. {
  155. audio.StopBgm();
  156. }
  157. }
  158. void StartBgmIfAllowed()
  159. {
  160. if (bgmStarted || !BgmEnabled)
  161. return;
  162. if (musicClip == null)
  163. musicClip = BuildMusicClip();
  164. musicSource.clip = musicClip;
  165. musicSource.loop = true;
  166. musicSource.Play();
  167. bgmStarted = true;
  168. }
  169. void StopBgm()
  170. {
  171. if (musicSource != null)
  172. musicSource.Stop();
  173. bgmStarted = false;
  174. }
  175. AudioClip GetSfxClip(GameSfx cue, int variant)
  176. {
  177. int safeVariant = Mathf.Max(0, variant);
  178. long key = ((long)cue << 32) | (uint)safeVariant;
  179. AudioClip clip;
  180. if (sfxClips.TryGetValue(key, out clip))
  181. return clip;
  182. clip = BuildSfxClip(cue, safeVariant);
  183. if (clip != null)
  184. sfxClips[key] = clip;
  185. return clip;
  186. }
  187. static AudioClip BuildMusicClip()
  188. {
  189. float length = BgmNotes.Length * BgmStepDuration;
  190. var data = new float[Mathf.CeilToInt(length * SampleRate)];
  191. for (int step = 0; step < BgmNotes.Length; step++)
  192. {
  193. float note = BgmNotes[step];
  194. float delay = step * BgmStepDuration;
  195. AddTone(data, note, 0.18f, Waveform.Triangle, 0.028f, delay);
  196. if (step % 4 == 1)
  197. AddTone(data, note / 4f, 0.28f, Waveform.Sine, 0.035f, delay);
  198. }
  199. return CreateClip("BGM_RetroFruitStand", data);
  200. }
  201. static AudioClip BuildSfxClip(GameSfx cue, int variant)
  202. {
  203. float[] data;
  204. switch (cue)
  205. {
  206. case GameSfx.Tap:
  207. data = NewBuffer(0.1f);
  208. AddTone(data, 520f, 0.06f, Waveform.Square, 0.06f, 0f);
  209. break;
  210. case GameSfx.Pick:
  211. data = NewBuffer(0.16f);
  212. AddTone(data, 660f, 0.07f, Waveform.Triangle, 0.1f, 0f);
  213. AddTone(data, 880f, 0.07f, Waveform.Triangle, 0.07f, 0.05f);
  214. break;
  215. case GameSfx.Drop:
  216. data = NewBuffer(0.13f);
  217. AddTone(data, 330f, 0.08f, Waveform.Sine, 0.12f, 0f, -90f);
  218. break;
  219. case GameSfx.Clear:
  220. data = NewBuffer(0.35f);
  221. for (int i = 0; i < 3; i++)
  222. {
  223. float frequency = Mathf.Min(12000f, 660f * Mathf.Pow(1.18f, i + variant));
  224. AddTone(data, frequency, 0.14f, Waveform.Triangle, 0.1f, i * 0.07f);
  225. }
  226. break;
  227. case GameSfx.Coin:
  228. data = NewBuffer(0.23f);
  229. AddTone(data, 1046f, 0.07f, Waveform.Square, 0.07f, 0f);
  230. AddTone(data, 1568f, 0.1f, Waveform.Square, 0.06f, 0.06f);
  231. break;
  232. case GameSfx.Win:
  233. data = NewBuffer(0.66f);
  234. AddTone(data, 523f, 0.22f, Waveform.Triangle, 0.11f, 0f);
  235. AddTone(data, 659f, 0.22f, Waveform.Triangle, 0.11f, 0.11f);
  236. AddTone(data, 784f, 0.22f, Waveform.Triangle, 0.11f, 0.22f);
  237. AddTone(data, 1046f, 0.22f, Waveform.Triangle, 0.11f, 0.33f);
  238. break;
  239. case GameSfx.Fail:
  240. data = NewBuffer(0.62f);
  241. AddTone(data, 440f, 0.26f, Waveform.Sawtooth, 0.08f, 0f);
  242. AddTone(data, 349f, 0.26f, Waveform.Sawtooth, 0.08f, 0.13f);
  243. AddTone(data, 262f, 0.26f, Waveform.Sawtooth, 0.08f, 0.26f);
  244. break;
  245. case GameSfx.Error:
  246. data = NewBuffer(0.16f);
  247. AddTone(data, 180f, 0.12f, Waveform.Square, 0.09f, 0f);
  248. break;
  249. case GameSfx.Buy:
  250. data = NewBuffer(0.27f);
  251. AddTone(data, 784f, 0.09f, Waveform.Square, 0.08f, 0f);
  252. AddTone(data, 1174f, 0.12f, Waveform.Square, 0.07f, 0.08f);
  253. break;
  254. case GameSfx.Spin:
  255. data = NewBuffer(0.09f);
  256. AddTone(data, 1200f, 0.04f, Waveform.Square, 0.05f, 0f);
  257. break;
  258. default:
  259. return null;
  260. }
  261. return CreateClip("SFX_" + cue + "_" + variant, data);
  262. }
  263. static float[] NewBuffer(float seconds)
  264. {
  265. return new float[Mathf.Max(1, Mathf.CeilToInt(seconds * SampleRate))];
  266. }
  267. static AudioClip CreateClip(string name, float[] data)
  268. {
  269. AudioClip clip = AudioClip.Create(name, data.Length, 1, SampleRate, false);
  270. clip.SetData(data, 0);
  271. return clip;
  272. }
  273. static void AddTone(float[] buffer, float frequency, float duration, Waveform waveform, float volume, float delay, float slide = 0f)
  274. {
  275. if (buffer == null || buffer.Length == 0 || duration <= 0f || volume <= 0f)
  276. return;
  277. int start = Mathf.RoundToInt(delay * SampleRate);
  278. int count = Mathf.Max(1, Mathf.RoundToInt(duration * SampleRate));
  279. float attack = Mathf.Min(0.012f, duration);
  280. float safeVolume = Mathf.Max(MinGain, volume);
  281. float endFrequency = Mathf.Max(40f, frequency + slide);
  282. float frequencyRatio = endFrequency / frequency;
  283. double phase = 0.0;
  284. for (int i = 0; i < count; i++)
  285. {
  286. int index = start + i;
  287. if (index < 0 || index >= buffer.Length)
  288. continue;
  289. float t = i / (float)SampleRate;
  290. float currentFrequency = Mathf.Approximately(slide, 0f)
  291. ? frequency
  292. : frequency * Mathf.Pow(frequencyRatio, t / duration);
  293. phase += 2.0 * Math.PI * currentFrequency / SampleRate;
  294. float gain;
  295. if (t < attack)
  296. {
  297. gain = attack > 0f
  298. ? MinGain * Mathf.Pow(safeVolume / MinGain, t / attack)
  299. : safeVolume;
  300. }
  301. else
  302. {
  303. float decayWindow = Mathf.Max(0.0001f, duration - attack);
  304. gain = safeVolume * Mathf.Pow(MinGain / safeVolume, (t - attack) / decayWindow);
  305. }
  306. buffer[index] += SampleWaveform(waveform, phase) * gain;
  307. }
  308. }
  309. static float SampleWaveform(Waveform waveform, double phase)
  310. {
  311. switch (waveform)
  312. {
  313. case Waveform.Square:
  314. return Math.Sin(phase) >= 0.0 ? 1f : -1f;
  315. case Waveform.Triangle:
  316. return (float)(2.0 / Math.PI * Math.Asin(Math.Sin(phase)));
  317. case Waveform.Sawtooth:
  318. double cycles = phase / (2.0 * Math.PI);
  319. return (float)(2.0 * (cycles - Math.Floor(cycles + 0.5)));
  320. default:
  321. return (float)Math.Sin(phase);
  322. }
  323. }
  324. }