using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Music
{
/// <summary>
/// 声音管理类
/// </summary>
public class AudioManager : MonoBehaviour {
public static AudioManager instance = null;
public static void initAudioManager()
{
if(instance == null)
{
GameObject obj = new GameObject();
obj.name = "bgSound";
instance = obj.AddComponent<AudioManager>();
instance.bgAudio = obj.AddComponent<AudioSource>();
instance.bgAudio.playOnAwake = false;
for(int i=0;i<5;i++)
{
GameObject obj1 = new GameObject("effeic");
AudioSource ads = obj1.AddComponent<AudioSource>();
ads.playOnAwake = false;
instance.effeics.Add(ads);
DontDestroyOnLoad(obj1);
}
print("音频管理 初始化成功");
}
}
private List<AudioSource> effeics = new List<AudioSource>();
private Dictionary<string, AudioClip> audios = new Dictionary<string, AudioClip>();
//背景音乐
private AudioSource bgAudio = null;
// Use this for initialization
void Start () {
//场景切换的时候 ,这个对象不销毁
DontDestroyOnLoad(this);
}
//通过路径,网络加载,也可以加本地
public void playerBackgroundSoundForUrl(string url, bool isLoop = true)
{
}
//直接通过名字播放,Resources.Load
public void playBackgroundSoundForName(string soundName,bool isLoop = true)
{
if(audios.ContainsKey(soundName))
{
bgAudio.clip = audios[soundName];
}
else
{
AudioClip clip = Resources.Load<AudioClip>(soundName);
bgAudio.clip = clip;
audios.Add(soundName, clip);
}
if (bgAudio.isPlaying) return;
bgAudio.loop = isLoop;
bgAudio.Play();
}
public void playBackgroundSound()
{
this.bgAudio.Play();
}
public bool PauseBackgroundSound
{
set {
if(value)
{
this.bgAudio.Pause();
}
else
{
this.bgAudio.UnPause();
}
}
}
public void StopBackgroundSound()
{
this.bgAudio.Stop();
}
public float BackgroundSoundVolume
{
set { this.bgAudio.volume = value; }
get { return this.bgAudio.volume; }
}
//音效
public void PlayerEffeict(string soundName,bool isLoop = false)
{
foreach(AudioSource ads in this.effeics)
{
if(!ads.isPlaying)
{
if (audios.ContainsKey(soundName))
{
ads.clip = audios[soundName];
}
else
{
AudioClip clip = Resources.Load<AudioClip>(soundName);
ads.clip = clip;
audios.Add(soundName, clip);
}
ads.loop = isLoop;
ads.Play();
break;
}
}
}
}
}
【unity】播放声音类
最新推荐文章于 2024-06-07 19:06:06 发布