TouhouLS/Assets/Code/AudioProvider.cs

80 lines
2.1 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using EntityNetwork;
public class AudioProvider : EntityBase, IAutoRegister
{
public static AudioProvider Instance;
public override void Awake() {
base.Awake();
Instance = this;
bgmSrc = GetComponent<AudioSource>();
UnkClip = Resources.Load<AudioClip>("Unk");
BunkClip = Resources.Load<AudioClip>("Bunk");
}
public float musicSpeed = 1f;
AudioSource bgmSrc;
public bool fastBGM = false;
[ContextMenu("Speedup Music for 5s")]
public void SpeedupForFiveSeconds() {
Instance.fastBGM = true;
timeUntilSlow = Time.time + 5f;
}
public static float timeUntilSlow = 0f;
public static void RequestFastMusic() {
Instance.fastBGM = true;
timeUntilSlow = Time.time + 3f;
}
static AudioClip UnkClip, BunkClip;
public static void Unk() {
PlaySFX(UnkClip, AudioHelper.AudioCategory.Fx);
}
public static void Bunk() {
PlaySFX(BunkClip, AudioHelper.AudioCategory.Fx);
}
public void Update() {
bgmSrc.loop = true;
bgmSrc.volume = AudioHelper.VolumeLevel(AudioHelper.AudioCategory.Music);
bgmSrc.pitch = fastBGM ? 1.3333f : 1f;
bgmSrc.outputAudioMixerGroup.audioMixer.SetFloat("ShiftPitch", fastBGM ? 0.75f : 1f);
if (Time.time > timeUntilSlow)
fastBGM = false;
}
int lastAudioFrame = 0;
public static void PlaySFX(AudioClip sfx, AudioHelper.AudioCategory category = AudioHelper.AudioCategory.Fx, float volume = 1.0f, bool sendRemote = true) {
if (sfx == null) return;
if (sendRemote)
Instance.RaiseEvent('s', true, AudioHelper.ByClip(sfx), (byte)category, volume);
else
Instance.InternallyPlaySFXEvent(AudioHelper.ByClip(sfx), (byte)category, volume);
}
[NetEvent('s')]
public void InternallyPlaySFXEvent(int sfxID, byte category, float volume) {
// Don't allow multiple audio sources to trigger at once
if (Time.frameCount == lastAudioFrame) return;
lastAudioFrame = Time.frameCount;
var clip = AudioHelper.ByID(sfxID);
AudioSource.PlayClipAtPoint(clip, Camera.main.transform.position, AudioHelper.VolumeLevel((AudioHelper.AudioCategory)category) * volume);
}
}