AndroidVolume.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class AndroidVolume : MonoBehaviour {
  5. const string AUDIO_SERVICE = "audio";
  6. const int STREAM_VOICE_CALL = 0;
  7. const int STREAM_SYSTEM = 1;
  8. const int STREAM_RING = 2;
  9. const int STREAM_MUSIC = 3;
  10. const int STREAM_ALARM = 4;
  11. const int STREAM_NOTIFICATION = 5;
  12. const int STREAM_DTMF = 8;
  13. public TextMesh text;
  14. int max = 0;
  15. int current = 0;
  16. private void Start()
  17. {
  18. }
  19. /// <summary>
  20. /// 获取Android系统音量值
  21. /// </summary>
  22. /// <returns></returns>
  23. public int GetMusicVolume()
  24. {
  25. AndroidJavaObject context = new AndroidJavaClass("com.unity3d.player.UnityPlayer").
  26. GetStatic<AndroidJavaObject>("currentActivity");
  27. using (AndroidJavaObject audioManager = context.Call<AndroidJavaObject>("getSystemService", AUDIO_SERVICE))
  28. {
  29. max = audioManager.Call<int>("getStreamMaxVolume", STREAM_MUSIC);
  30. current = audioManager.Call<int>("getStreamVolume", STREAM_MUSIC);
  31. Debug.Log("当前音量:" + current);
  32. }
  33. return current;
  34. }
  35. private void Update()
  36. {
  37. // text.text = GetMusicVolume().ToString();
  38. }
  39. /// <summary>
  40. /// 设置Android系统音量值
  41. /// </summary>
  42. /// <param name="volume"></param>
  43. public void SetMusicVolume(int volume)
  44. {
  45. current -= volume;
  46. AndroidJavaObject context = new AndroidJavaClass("com.unity3d.player.UnityPlayer").
  47. GetStatic<AndroidJavaObject>("currentActivity");
  48. using (AndroidJavaObject audioManager = context.Call<AndroidJavaObject>("getSystemService", AUDIO_SERVICE))
  49. {
  50. audioManager.Call("setStreamVolume", STREAM_MUSIC, (int)current, 0);
  51. }
  52. }
  53. /// <summary>
  54. /// 设置Android系统音量值
  55. /// </summary>
  56. /// <param name="volume"></param>
  57. public void SetMusicVolumeAdd(int volume)
  58. {
  59. current += volume;
  60. AndroidJavaObject context = new AndroidJavaClass("com.unity3d.player.UnityPlayer").
  61. GetStatic<AndroidJavaObject>("currentActivity");
  62. using (AndroidJavaObject audioManager = context.Call<AndroidJavaObject>("getSystemService", AUDIO_SERVICE))
  63. {
  64. audioManager.Call("setStreamVolume", STREAM_MUSIC, (int)current, 0);
  65. }
  66. }
  67. }