1
0

DeviceVolume.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System.Runtime.InteropServices;
  2. using UnityEngine;
  3. namespace Unity.Services.Analytics.Platform
  4. {
  5. static class DeviceVolumeProvider
  6. {
  7. #if UNITY_IOS && !UNITY_EDITOR
  8. [DllImport("__Internal")]
  9. static extern float unity_services_analytics_get_device_volume();
  10. #endif
  11. internal static float? GetDeviceVolume()
  12. {
  13. #if UNITY_IOS && !UNITY_EDITOR
  14. // Provided by the plugin in Runtime/Plugins/iOS/VolumeIOSPlugin.mm
  15. return unity_services_analytics_get_device_volume();
  16. #elif UNITY_ANDROID && !UNITY_EDITOR
  17. // The below code should be equivalent to the following Android code. Note that constants have been converted to their raw values,
  18. // as documented in the android docs.
  19. // ---
  20. // Activity activity = UnityPlayer.currentActivity; // Get the current activity as provided by Unity
  21. // AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE); // Get the system audio service from the activity
  22. // double volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); // Get the music/media audio stream volume
  23. AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  24. AndroidJavaObject activity = jc.GetStatic<AndroidJavaObject>("currentActivity");
  25. AndroidJavaObject audioManager = activity.Call<AndroidJavaObject>("getSystemService", "audio");
  26. int STREAM_MUSIC_rawValue = 3; // See android docs for STREAM_MUSIC constant on AudioManager
  27. int volume = audioManager.Call<int>("getStreamVolume", STREAM_MUSIC_rawValue);
  28. int maxVolume = audioManager.Call<int>("getStreamMaxVolume", STREAM_MUSIC_rawValue);
  29. return (float) volume / (float) maxVolume;
  30. #else
  31. // Other platforms don't support device volume at this time.
  32. return null;
  33. #endif
  34. }
  35. }
  36. }