MusicManager.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using UnityEngine;
  3. using GFGGame.Launcher;
  4. namespace GFGGame
  5. {
  6. public class MusicManager : SingletonMonoBase<MusicManager>
  7. {
  8. private AudioSource _player;
  9. private string _currentName;
  10. private bool _isOn = true;
  11. public bool isOn
  12. {
  13. get
  14. {
  15. return _isOn;
  16. }
  17. set
  18. {
  19. if(_isOn != value)
  20. {
  21. _isOn = value;
  22. if(_isOn)
  23. {
  24. if(_currentName != null)
  25. {
  26. Play(_currentName, true);
  27. }
  28. }
  29. else
  30. {
  31. Stop();
  32. }
  33. LocalCache.SetBool(LauncherConfig.MUSIC_KEY, _isOn);
  34. }
  35. }
  36. }
  37. private void Awake()
  38. {
  39. _player = this.gameObject.AddComponent<AudioSource>();
  40. _player.loop = true;
  41. }
  42. private void Start()
  43. {
  44. }
  45. private void Update()
  46. {
  47. }
  48. public void Play(string path, bool must = false)
  49. {
  50. if(_currentName != path || must)
  51. {
  52. _currentName = path;
  53. if(_isOn)
  54. {
  55. AudioClip clip = GFGAsset.Load<AudioClip>(path);
  56. _player.clip = clip;
  57. _player.Play();
  58. }
  59. }
  60. }
  61. public void PlayByUrl(string url, bool must = false)
  62. {
  63. if (_currentName != name || must)
  64. {
  65. _currentName = name;
  66. //如果是播人声是不受音乐开关影响
  67. //if (_isOn)
  68. //{
  69. AudioClip clip = GFGAsset.Load<AudioClip>(url);
  70. _player.clip = clip;
  71. _player.PlayOneShot(clip);
  72. //}
  73. }
  74. }
  75. public float GetSoundTime()
  76. {
  77. if (_player.clip != null)
  78. {
  79. return _player.clip.length;
  80. }
  81. return 0;
  82. }
  83. public void Pause()
  84. {
  85. _player.Pause();
  86. }
  87. public void UnPause()
  88. {
  89. _player.UnPause();
  90. }
  91. public void Stop()
  92. {
  93. _player.Stop();
  94. }
  95. }
  96. }