Unity组件开发--背景音乐管理器

发布时间:2024年01月11日

1.背景音乐作为一个独立的节点:

2.通过Url加载背景音乐:运行后添加AudioSource组件

using DG.Tweening;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Analytics;
using UnityEngine.Networking;

public class PlaySceneBgm : MonoBehaviour
{
    [HideInInspector]
    public AudioSource audioS;
    [HideInInspector]
    public string url;
    [HideInInspector]
    public static PlaySceneBgm Instance;
    private bool isLoaded;
    // Start is called before the first frame update
    [HideInInspector]
    public string defaultbgmUrl = "";

    private float playCurMusicProgress = 0;
    private bool isPaused = false;
    private string lastPlayUrl = "";
    public void SetUrl(string audioLink)
    {

        if (url == audioLink)
        {
            return;
        }
        this.playCurMusicProgress = 0;
        url = audioLink;
        StartCoroutine(GetAudioClip(true));
    }


    
    // Start is called before the first frame update
    void Awake()
    {

        audioS = gameObject.AddComponent<AudioSource>();
        audioS.playOnAwake = false;
        audioS.loop = true;
        audioS.volume = 0.25f;
        Instance = this;

        EventManager.Instance.AddListener(EventName.OnSceneLoaded, (s, e) => {
            if (!string.ReferenceEquals(PlayerData.Instance.TemplateId.ToString(), null))
            {

                url = "..........";
            }
            defaultbgmUrl = url;
            if (PlayerData.Instance.isRunningPC)
            {
                Debug.Log("当前是在PC上播放背景音乐");
                StartCoroutine(GetAudioClip(true));
            }
            
        });
        
        EventManager.Instance.AddListener(EventName.stopSceneBgm, stopSceneBgm);
        EventManager.Instance.AddListener(EventName.playSceneBgm, playSceneBgm);
        EventManager.Instance.AddListener(EventName.changeSceneBgmValue, changeSceneBgmValue);
    }



    public float getCurMusicPro() {

        return this.playCurMusicProgress;
    }

    public void stopSceneBgm(object sender, EventArgs e) {
        if (isLoaded && audioS.clip != null)
        {
            audioS.Pause();
            
            isPaused = true;
        }
    }

    public bool getPlayState() {

        if (isLoaded && audioS.clip != null)
        {
            return audioS.isPlaying;
        }
        else {

            return false;
        }
    }

    public void playSceneBgm(object sender, EventArgs e)
    {
        if (isLoaded && audioS.clip != null)
        {

            audioS.Play();
        }
        else {

            StartCoroutine(GetAudioClip(true));
        }
    }

    // 恢复音频播放
    public void resumeSceneBgm()
    {
        if (isLoaded && audioS.clip != null)
        {
            
            if (isPaused)
            {
                
                StartCoroutine(ResumeWithDelay());
                //url = lastPlayUrl;
                //StartCoroutine(GetAudioClip(true));
                isPaused = false;
            }
        }
        
    }

    private IEnumerator ResumeWithDelay()
    {
        yield return new WaitForSeconds(0.1f); // 添加 0.1 秒的延迟
        if (isLoaded && audioS.clip != null)
        {
            audioS.UnPause();
        }
            
    }

    public void changeSceneBgmValue(object sender, EventArgs e)
    {
        var data = e as changeBgmVolume;
        if (data != null) {

            audioS.volume = data.volume;
        }
    }

    IEnumerator GetAudioClip(bool isPlay = false)
    {
        this.playCurMusicProgress = 0;
        Debug.Log("音频加载11111" + url);
        if (UtilsFunc.IsURL(url) == false)
        {
            yield break;
        }

        var audioType = AudioType.MPEG;
        if (UtilsFunc.UrlExtension(url, "*.mp3") || UtilsFunc.UrlExtension(url, "*.MP3"))
        {
            audioType = AudioType.MPEG;
        }
        else if (UtilsFunc.UrlExtension(url, "*.wav"))
        {
            audioType = AudioType.WAV;
        }
        else if (UtilsFunc.UrlExtension(url, "*.ogg"))
        {
            audioType = AudioType.OGGVORBIS;
        }

        Debug.Log("音频加载0000" + url);
        //using (var uwr = UnityWebRequestMultimedia.GetAudioClip(url, audioType))
        //{
        //    yield return uwr.SendWebRequest();
        //    if (uwr.result != UnityWebRequest.Result.Success)
        //    {
        //        Debug.LogError("音频加载8888"+uwr.error);
        //        yield break;
        //    }
        //    Debug.Log("音频加载22222" + url);
        //    isLoaded = true;
        //    AudioClip clip = DownloadHandlerAudioClip.GetContent(uwr);
        //    // use audio clip
        //    // 在异步线程中进行加载和分配
        //    audioS.clip = clip;
        //    lastPlayUrl = url;
        //    StartCoroutine(LoadAudioClip(isPlay));    
        //}
        WWW _www = new WWW(url);
        yield return _www;
        if (_www.error == null)
        {
            isLoaded = true;
            AudioClip _audioClip = _www.GetAudioClip(true, true, audioType);
            audioS.clip = _audioClip;
            lastPlayUrl = url;
            StartCoroutine(LoadAudioClip(isPlay));    
        }
        else
        {
            Debug.Log(_www.error);
            Debug.LogError("音频加载报错" + _www.error);
            yield break;
        }

    }



    public void WebRequestPlayMP3()
    {
        
        StartCoroutine(IELoadExternalAudioWebRequest(url, AudioType.MPEG));
    }
    public void WWWPlayMP3()
    {
        
        StartCoroutine(IELoadExternalAudioWWW(url, AudioType.MPEG));
    }
    public void WebRequestPlayWAV()
    {
        
        StartCoroutine(IELoadExternalAudioWebRequest(url, AudioType.WAV));
    }
    public void WWWPlayWAV()
    {
        
        StartCoroutine(IELoadExternalAudioWWW(url, AudioType.WAV));
    }

    private IEnumerator IELoadExternalAudioWebRequest(string _url, AudioType _audioType)
    {
        UnityWebRequest _unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(_url, _audioType);
        yield return _unityWebRequest.SendWebRequest();
        if (_unityWebRequest.isHttpError || _unityWebRequest.isNetworkError)
        {
            Debug.Log(_unityWebRequest.error.ToString());
        }
        else
        {
            AudioClip _audioClip = DownloadHandlerAudioClip.GetContent(_unityWebRequest);
            audioS.clip = _audioClip;
            audioS.Play();
        }
    }

    private IEnumerator IELoadExternalAudioWWW(string _url, AudioType _audioType)
    {

        this.playCurMusicProgress = 0;
        Debug.Log("音频加载11111" + url);
        if (UtilsFunc.IsURL(url) == false)
        {
            yield break;
        }

        WWW _www = new WWW(_url);
        yield return _www;
        if (_www.error == null)
        {
            AudioClip _audioClip = _www.GetAudioClip(true, true, _audioType);
            audioS.clip = _audioClip;
            audioS.Play();
        }
        else
        {
            Debug.Log(_www.error);
        }
    }


    private IEnumerator LoadAudioClip(bool isPlay = false)
    {

        yield return audioS.clip.LoadAudioData();
        yield return new WaitUntil(() => audioS.clip.loadState == AudioDataLoadState.Loaded);
        Debug.Log("音频加载状态......." + audioS.clip.loadState);
        if (isPlay && audioS.clip.loadState == AudioDataLoadState.Loaded)
        {
            audioS.Play();
        }

        
    }

    // Update is called once per frame
    void Update()
    {
        if (audioS.clip == null) {
            return;
        }

        // 获取音频播放的进度
        float progress = audioS.time / audioS.clip.length;

        // 输出播放进度
        //Debug.Log("当前歌曲播放进度:" + progress);
        this.playCurMusicProgress = progress;

    }
}

3.外部通过PlaySceneBgm.Instance 调用相关接口:

文章来源:https://blog.csdn.net/woshiyuyanjia/article/details/135520992
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。