Unity 音频管理

做2D项目比较适合

音频文件位置默认 Resources/Audio

using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;

public class Sound
{
    public AudioManager audioManager;
    public string name;
    public AudioClip clip;
    public AudioSource source;
    public Action<Sound> callback;
    public bool loop;
    public bool interrupts;
    private HashSet<Sound> interruptedSounds =
        new HashSet<Sound> ();

    //声音播放进度
    public float progress {
        get {
            if (source == null || clip == null)
                return 0f;
            return (float)source.timeSamples / (float)clip.samples;
        }
    }

    ///如果声音完成播放,则返回true
    ///循环声音 返回 false
    public bool finished {
        get {

            return !loop && progress >= 1f;
        }
    }
    // 播放
    public bool playing {
        get {
            return source != null && source.isPlaying;
        } 
        set {
            if (value) {
                audioManager.RegisterSound(this);
            }
            PlayOrPause(value, interrupts);
        }
    }
    /// <summary>
    /// 注册音频
    /// </summary>
    /// <param name="newName">音频名字 必须有这个音频</param>   
     public Sound(string newName)
     {
        name = newName;
        clip = (AudioClip)Resources.Load("Audio/"+name, typeof(AudioClip));
        if (clip == null)
               Debug.log("音频不存在");
    }

    public void Update() {
        if (source != null)
            source.loop = loop;
        if (finished)
            Finish();
    }
      /// <summary>
    /// 播放或者暂停 
    /// </summary>
    /// <param name="play">播放或者暂停</param>
    /// <param name="pauseOthers"> 其他音频</param>
    public void PlayOrPause(bool play, bool pauseOthers) {
        if (pauseOthers) {
            if (play) {
                interruptedSounds = new HashSet<Sound>(audioManager.sounds.Where(snd => snd.playing &&
                                                                                        snd != this));
            }
            interruptedSounds.ToList().ForEach(sound => sound.PlayOrPause(!play, false));
        }
        if (play && !source.isPlaying) {
            source.Play();
        } else {
            source.Pause();
        }
    }

    ///在声音完成时执行必要的操作
    public void Finish() {
        PlayOrPause(false, true);
        if (callback != null) 
            callback(this);
        MonoBehaviour.Destroy(source);
        source = null;
    }

    //重新开始声音
    public void Reset() {
        source.time = 0f;
    }
}

要挂载在对象上

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;

public class AudioManager : MonoBehaviour
{
    public static AudioManager m_Instance = null;
    public static AudioManager Instance
    {        
        get
        {

            if (m_Instance == null)
            {
               //自己找合适的对象名称
                if (GameObject.Find("GameManager").GetComponent<AudioManager>() == null)
                {
                    IntAudio();
                }
            }
            return GameObject.Find("GameManager").GetComponent<AudioManager>();
           // return Camera.main.GetComponent<AudioManager>();
        }
    }
    public HashSet<Sound> sounds =
       new HashSet<Sound> ();

    static void IntAudio()
    {
        GameObject.Find("GameManager").AddComponent<AudioManager>();
    }
    /// <summary>
    /// 播放一个新的声音,注册它,给它指定的属性,并开始播放它
    /// </summary>
    /// <param name="名字"></param>
    /// <param name="循环"></param>
    /// <param name="中断其他"></param>
    /// <param name="行为"></param>
    /// <returns></returns>
    public Sound PlayNewSound(string soundName,bool loop=false, bool interrupts=false, Action<Sound> callback=null) {
        Sound sound = NewSound(soundName, loop, interrupts, callback);
        sound.playing = true;
        return  sound;
    }

    /// <summary>
    /// 创建一个新的声音,注册它,并给它指定的属性 不播放
    /// </summary>
    /// <param name="名字"></param>
    /// <param name="循环"></param>
    /// <param name="中断其他"></param>
    /// <param name="行为"></param>
    /// <returns></returns>
    public Sound NewSound(string soundName, bool loop=false, bool interrupts=false, Action<Sound> callback=null) {
        Sound sound = new Sound(soundName);
        RegisterSound(sound);
        sound.loop = loop;
        sound.interrupts = interrupts;
        sound.callback = callback;
        return sound;
    }
    //注册一个音频播放组件
    public void RegisterSound(Sound sound) {
        sounds.Add(sound);
        sound.audioManager = this;
        if (sound.source == null) {
            AudioSource source = gameObject.AddComponent<AudioSource>();
            source.clip = sound.clip;
            sound.source = source;
        }
    }

    private void Update() {
        sounds.ToList().ForEach(sound => {
            sound.Update();                 
        });
    }
}

例子

// 注册
  private Sound Bg;
 //实例
 Bg = AudioManager.Instance.NewSound("Dungeon", loop: true);
//是否播放
 Bg.playing = false;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值