| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394 |
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- public enum GameSfx
- {
- Tap,
- Pick,
- Drop,
- Clear,
- Coin,
- Win,
- Fail,
- Error,
- Buy,
- Spin
- }
- [DisallowMultipleComponent]
- public class GameAudio : MonoBehaviour
- {
- const int SampleRate = 44100;
- const float BgmStepDuration = 0.3f;
- const float MinGain = 0.0001f;
- static readonly float[] BgmNotes =
- {
- 523f, 659f, 784f, 659f, 587f, 698f, 880f, 698f,
- 523f, 659f, 784f, 1046f, 880f, 784f, 659f, 587f
- };
- enum Waveform
- {
- Sine,
- Square,
- Triangle,
- Sawtooth
- }
- static GameAudio instance;
- AudioSource musicSource;
- AudioSource sfxSource;
- AudioClip musicClip;
- readonly Dictionary<long, AudioClip> sfxClips = new Dictionary<long, AudioClip>();
- bool bgmStarted;
- bool interacted;
- public static bool BgmEnabled
- {
- get
- {
- if (!Application.isPlaying)
- return false;
- SaveService.EnsureLoaded();
- return SaveService.Data.settings.bgm;
- }
- }
- public static bool SfxEnabled
- {
- get
- {
- if (!Application.isPlaying)
- return false;
- SaveService.EnsureLoaded();
- return SaveService.Data.settings.sfx;
- }
- }
- [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
- static void Bootstrap()
- {
- Ensure();
- }
- static GameAudio Ensure()
- {
- if (!Application.isPlaying)
- return null;
- if (instance != null)
- return instance;
- var go = new GameObject("GameAudio");
- DontDestroyOnLoad(go);
- return go.AddComponent<GameAudio>();
- }
- void Awake()
- {
- if (instance != null && instance != this)
- {
- Destroy(gameObject);
- return;
- }
- instance = this;
- DontDestroyOnLoad(gameObject);
- musicSource = gameObject.AddComponent<AudioSource>();
- musicSource.playOnAwake = false;
- musicSource.loop = true;
- musicSource.spatialBlend = 0f;
- musicSource.volume = 1f;
- sfxSource = gameObject.AddComponent<AudioSource>();
- sfxSource.playOnAwake = false;
- sfxSource.loop = false;
- sfxSource.spatialBlend = 0f;
- sfxSource.volume = 1f;
- }
- void OnDestroy()
- {
- if (instance == this)
- instance = null;
- }
- void Update()
- {
- if (bgmStarted || interacted)
- return;
- if (Input.anyKeyDown || Input.touchCount > 0)
- {
- interacted = true;
- StartBgmIfAllowed();
- }
- }
- public static void NotifyInteraction()
- {
- GameAudio audio = Ensure();
- if (audio == null)
- return;
- audio.interacted = true;
- audio.StartBgmIfAllowed();
- }
- public static void PlayTap()
- {
- PlaySfx(GameSfx.Tap);
- }
- public static void PlaySfx(GameSfx cue, int variant = 0)
- {
- GameAudio audio = Ensure();
- if (audio == null)
- return;
- audio.interacted = true;
- audio.StartBgmIfAllowed();
- if (!SfxEnabled)
- return;
- AudioClip clip = audio.GetSfxClip(cue, variant);
- if (clip != null)
- audio.sfxSource.PlayOneShot(clip);
- }
- public static void StopBgmImmediate()
- {
- if (instance == null)
- return;
- instance.StopBgm();
- }
- public static void RefreshSettings()
- {
- GameAudio audio = Ensure();
- if (audio == null)
- return;
- if (BgmEnabled)
- {
- if (audio.interacted)
- audio.StartBgmIfAllowed();
- }
- else
- {
- audio.StopBgm();
- }
- }
- void StartBgmIfAllowed()
- {
- if (bgmStarted || !BgmEnabled)
- return;
- if (musicClip == null)
- musicClip = BuildMusicClip();
- musicSource.clip = musicClip;
- musicSource.loop = true;
- musicSource.Play();
- bgmStarted = true;
- }
- void StopBgm()
- {
- if (musicSource != null)
- musicSource.Stop();
- bgmStarted = false;
- }
- AudioClip GetSfxClip(GameSfx cue, int variant)
- {
- int safeVariant = Mathf.Max(0, variant);
- long key = ((long)cue << 32) | (uint)safeVariant;
- AudioClip clip;
- if (sfxClips.TryGetValue(key, out clip))
- return clip;
- clip = BuildSfxClip(cue, safeVariant);
- if (clip != null)
- sfxClips[key] = clip;
- return clip;
- }
- static AudioClip BuildMusicClip()
- {
- float length = BgmNotes.Length * BgmStepDuration;
- var data = new float[Mathf.CeilToInt(length * SampleRate)];
- for (int step = 0; step < BgmNotes.Length; step++)
- {
- float note = BgmNotes[step];
- float delay = step * BgmStepDuration;
- AddTone(data, note, 0.18f, Waveform.Triangle, 0.028f, delay);
- if (step % 4 == 1)
- AddTone(data, note / 4f, 0.28f, Waveform.Sine, 0.035f, delay);
- }
- return CreateClip("BGM_RetroFruitStand", data);
- }
- static AudioClip BuildSfxClip(GameSfx cue, int variant)
- {
- float[] data;
- switch (cue)
- {
- case GameSfx.Tap:
- data = NewBuffer(0.1f);
- AddTone(data, 520f, 0.06f, Waveform.Square, 0.06f, 0f);
- break;
- case GameSfx.Pick:
- data = NewBuffer(0.16f);
- AddTone(data, 660f, 0.07f, Waveform.Triangle, 0.1f, 0f);
- AddTone(data, 880f, 0.07f, Waveform.Triangle, 0.07f, 0.05f);
- break;
- case GameSfx.Drop:
- data = NewBuffer(0.13f);
- AddTone(data, 330f, 0.08f, Waveform.Sine, 0.12f, 0f, -90f);
- break;
- case GameSfx.Clear:
- data = NewBuffer(0.35f);
- for (int i = 0; i < 3; i++)
- {
- float frequency = Mathf.Min(12000f, 660f * Mathf.Pow(1.18f, i + variant));
- AddTone(data, frequency, 0.14f, Waveform.Triangle, 0.1f, i * 0.07f);
- }
- break;
- case GameSfx.Coin:
- data = NewBuffer(0.23f);
- AddTone(data, 1046f, 0.07f, Waveform.Square, 0.07f, 0f);
- AddTone(data, 1568f, 0.1f, Waveform.Square, 0.06f, 0.06f);
- break;
- case GameSfx.Win:
- data = NewBuffer(0.66f);
- AddTone(data, 523f, 0.22f, Waveform.Triangle, 0.11f, 0f);
- AddTone(data, 659f, 0.22f, Waveform.Triangle, 0.11f, 0.11f);
- AddTone(data, 784f, 0.22f, Waveform.Triangle, 0.11f, 0.22f);
- AddTone(data, 1046f, 0.22f, Waveform.Triangle, 0.11f, 0.33f);
- break;
- case GameSfx.Fail:
- data = NewBuffer(0.62f);
- AddTone(data, 440f, 0.26f, Waveform.Sawtooth, 0.08f, 0f);
- AddTone(data, 349f, 0.26f, Waveform.Sawtooth, 0.08f, 0.13f);
- AddTone(data, 262f, 0.26f, Waveform.Sawtooth, 0.08f, 0.26f);
- break;
- case GameSfx.Error:
- data = NewBuffer(0.16f);
- AddTone(data, 180f, 0.12f, Waveform.Square, 0.09f, 0f);
- break;
- case GameSfx.Buy:
- data = NewBuffer(0.27f);
- AddTone(data, 784f, 0.09f, Waveform.Square, 0.08f, 0f);
- AddTone(data, 1174f, 0.12f, Waveform.Square, 0.07f, 0.08f);
- break;
- case GameSfx.Spin:
- data = NewBuffer(0.09f);
- AddTone(data, 1200f, 0.04f, Waveform.Square, 0.05f, 0f);
- break;
- default:
- return null;
- }
- return CreateClip("SFX_" + cue + "_" + variant, data);
- }
- static float[] NewBuffer(float seconds)
- {
- return new float[Mathf.Max(1, Mathf.CeilToInt(seconds * SampleRate))];
- }
- static AudioClip CreateClip(string name, float[] data)
- {
- AudioClip clip = AudioClip.Create(name, data.Length, 1, SampleRate, false);
- clip.SetData(data, 0);
- return clip;
- }
- static void AddTone(float[] buffer, float frequency, float duration, Waveform waveform, float volume, float delay, float slide = 0f)
- {
- if (buffer == null || buffer.Length == 0 || duration <= 0f || volume <= 0f)
- return;
- int start = Mathf.RoundToInt(delay * SampleRate);
- int count = Mathf.Max(1, Mathf.RoundToInt(duration * SampleRate));
- float attack = Mathf.Min(0.012f, duration);
- float safeVolume = Mathf.Max(MinGain, volume);
- float endFrequency = Mathf.Max(40f, frequency + slide);
- float frequencyRatio = endFrequency / frequency;
- double phase = 0.0;
- for (int i = 0; i < count; i++)
- {
- int index = start + i;
- if (index < 0 || index >= buffer.Length)
- continue;
- float t = i / (float)SampleRate;
- float currentFrequency = Mathf.Approximately(slide, 0f)
- ? frequency
- : frequency * Mathf.Pow(frequencyRatio, t / duration);
- phase += 2.0 * Math.PI * currentFrequency / SampleRate;
- float gain;
- if (t < attack)
- {
- gain = attack > 0f
- ? MinGain * Mathf.Pow(safeVolume / MinGain, t / attack)
- : safeVolume;
- }
- else
- {
- float decayWindow = Mathf.Max(0.0001f, duration - attack);
- gain = safeVolume * Mathf.Pow(MinGain / safeVolume, (t - attack) / decayWindow);
- }
- buffer[index] += SampleWaveform(waveform, phase) * gain;
- }
- }
- static float SampleWaveform(Waveform waveform, double phase)
- {
- switch (waveform)
- {
- case Waveform.Square:
- return Math.Sin(phase) >= 0.0 ? 1f : -1f;
- case Waveform.Triangle:
- return (float)(2.0 / Math.PI * Math.Asin(Math.Sin(phase)));
- case Waveform.Sawtooth:
- double cycles = phase / (2.0 * Math.PI);
- return (float)(2.0 * (cycles - Math.Floor(cycles + 0.5)));
- default:
- return (float)Math.Sin(phase);
- }
- }
- }
|