1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class SoundManager : MonoBehaviour
{
    private static SoundManager _Instance = null;
 
    public static SoundManager I
    {
        get
        {
            if (_Instance == null)
            {
                Debug.Log("instance is null");
            }
            return _Instance;
        }
    }
 
    void Awake()
    {
        _Instance = this;
    }
 
 
    public int audioSourceCount = 3;
 
    [SerializeField]
    [Header("clips"), Tooltip("오디오 클립들")]
    public AudioClip[] BGMs = new AudioClip[2];
    public AudioClip[] SFXs = new AudioClip[3];
 
 
    private AudioSource BGMsource;
    private AudioSource[] SFXsource;
 
    public delegate void CallBack();
    CallBack BGMendCallBack;
 
    void OnEnable()
    {
        float volume = PlayerPrefs.GetFloat("volumeBGM"1);
 
        BGMsource = gameObject.AddComponent<AudioSource>();
        BGMsource.volume = volume;
        BGMsource.playOnAwake = false;
        BGMsource.loop = true;
 
        //sfx 소스 초기화
        SFXsource = new AudioSource[audioSourceCount];
 
        volume = PlayerPrefs.GetFloat("volumeSFX"1);
 
        for (int i = 0; i < SFXsource.Length; i++)
        {
            SFXsource[i] = gameObject.AddComponent<AudioSource>();
            SFXsource[i].playOnAwake = false;
            SFXsource[i].volume = volume;
        }
 
 
        ChangeBGM("Game"false);
    }
 
    /**********SFX***********/
 
    public void PlaySFX(string name, bool loop = falsefloat pitch = 1)//효과음 재생
    {
        for (int i = 0; i < SFXs.Length; i++)
        {
            if (SFXs[i].name == name)
            {
                AudioSource a = GetEmptySource();
                a.loop = loop;
                a.pitch = pitch;
                a.clip = SFXs[i];
                a.Play();
                return;
            }
        }
    }
 
    public void StopSFXByName(string name)
    {
        for (int i = 0; i < SFXsource.Length; i++)
        {
            if (SFXsource[i].clip.name == name)
                SFXsource[i].Stop();
        }
    }
 
    private AudioSource GetEmptySource()//비어있는 오디오 소스 반환
    {
        int lageindex = 0;
        float lageProgress = 0;
        for (int i = 0; i < SFXsource.Length; i++)
        {
            if (!SFXsource[i].isPlaying)
            {
                return SFXsource[i];
            }
 
            //만약 비어있는 오디오 소스를 못찿으면 가장 진행도가 높은 오디오 소스 반환(루프중인건 스킵)
 
            float progress = SFXsource[i].time / SFXsource[i].clip.length;
            if (progress > lageProgress && !SFXsource[i].loop)
            {
                lageindex = i;
                lageProgress = progress;
            }
        }
        return SFXsource[lageindex];
    }
 
    /**********BGM***********/
 
    private AudioClip changeClip;//바뀌는 클립
    private bool isChanging = false;
    private float startTime;
 
 
    [SerializeField]
    [Header("Changing speed"), Tooltip("브금 바꾸는 속도")]
    public float ChangingSpeed;
 
    public void ChangeBGM(string name, bool isSmooth = false, CallBack callback = null)//브금 변경 (브금이름 , 부드럽게 바꾸기)
    {
        BGMendCallBack = callback;
 
        changeClip = null;
        for (int i = 0; i < BGMs.Length; i++)//브금 클립 탐색
        {
            if (BGMs[i].name == name)
            {
                changeClip = BGMs[i];
            }
        }
 
        if (changeClip == null)//없으면 탈주
            return;
 
        if (!isSmooth)
        {
            BGMsource.clip = changeClip;
            BGMsource.Play();
        }
        else
        {
            startTime = Time.time;
            isChanging = true;
        }
    }
 
    public string GetRandomBGMName()
    {
        return BGMs[Random.Range(0, BGMs.Length)].name;
    }
 
    private void Update()
    {
        if (!isChanging) return;
 
        float progress = (Time.time - startTime) * ChangingSpeed;//부드러운 오디오 전환
        BGMsource.volume = Mathf.Lerp(PlayerPrefs.GetFloat("volumeBGM"1), 0, progress);
 
        if (progress > 1)
        {
            isChanging = false;
            BGMsource.volume = PlayerPrefs.GetFloat("volumeBGM"1);
            BGMsource.clip = changeClip;
            BGMsource.Play();
        }
    }
 
    public void StopBGM()
    {
        BGMsource.Stop();
    }
 
    public void SetPitch(float pitch)
    {
        BGMsource.pitch = pitch;
    }
 
 
    //비주얼라이저용 오디오 샘플
    public float[] GetAudioSample(int sampleCount, FFTWindow fft)
    {
        float[] samples = new float[sampleCount];
 
        BGMsource.GetSpectrumData(samples, 0, fft);
 
        if (samples != null)
            return samples;
        else
            return null;
    }
 
    //볼륨
 
    public void changeBGMVolume(float volume)
    {
        PlayerPrefs.SetFloat("volumeBGM", volume);
        BGMsource.volume = volume;
    }
 
 
    public void changeSFXVolume(float volume)
    {
        PlayerPrefs.SetFloat("volumeSFX", volume);
        for (int i = 0; i < SFXsource.Length; i++)
        {
            SFXsource[i].volume = volume;
        }
    }
}
 
cs



여러번 프로젝트에 사용하며 천천히 많은부분을 고쳐 나갔는데


(아직도 남아 있을지 모르지만) BGM관련 버그 고치고

새로운 기능도 몇가지 추가했다.


이름으로 브금이랑 효과음을 호출할 수 있다.

효과음호출할때 피치를 조정할 수 있고

비주얼라이저같은걸 만들기 위한 샘플을 받아오는 함수도 있다.


'내가 만든거' 카테고리의 다른 글

길따라 로봇 road robot 제작기(BIC 전시기)  (1) 2019.09.25
등산 시뮬레이터  (0) 2018.06.23
맵 에디터 !!!!  (0) 2018.05.11
유니티 스와이프  (0) 2018.02.20
마인크래프트 만들었다  (0) 2017.05.24
블로그 이미지

stuban

ㅇ.ㅇ

,