using System.Collections; using System.Collections.Generic; using UnityEngine; public class AndroidVolume : MonoBehaviour { const string AUDIO_SERVICE = "audio"; const int STREAM_VOICE_CALL = 0; const int STREAM_SYSTEM = 1; const int STREAM_RING = 2; const int STREAM_MUSIC = 3; const int STREAM_ALARM = 4; const int STREAM_NOTIFICATION = 5; const int STREAM_DTMF = 8; public TextMesh text; int max = 0; int current = 0; private void Start() { } /// /// 获取Android系统音量值 /// /// public int GetMusicVolume() { AndroidJavaObject context = new AndroidJavaClass("com.unity3d.player.UnityPlayer"). GetStatic("currentActivity"); using (AndroidJavaObject audioManager = context.Call("getSystemService", AUDIO_SERVICE)) { max = audioManager.Call("getStreamMaxVolume", STREAM_MUSIC); current = audioManager.Call("getStreamVolume", STREAM_MUSIC); Debug.Log("当前音量:" + current); } return current; } private void Update() { // text.text = GetMusicVolume().ToString(); } /// /// 设置Android系统音量值 /// /// public void SetMusicVolume(int volume) { current -= volume; AndroidJavaObject context = new AndroidJavaClass("com.unity3d.player.UnityPlayer"). GetStatic("currentActivity"); using (AndroidJavaObject audioManager = context.Call("getSystemService", AUDIO_SERVICE)) { audioManager.Call("setStreamVolume", STREAM_MUSIC, (int)current, 0); } } /// /// 设置Android系统音量值 /// /// public void SetMusicVolumeAdd(int volume) { current += volume; AndroidJavaObject context = new AndroidJavaClass("com.unity3d.player.UnityPlayer"). GetStatic("currentActivity"); using (AndroidJavaObject audioManager = context.Call("getSystemService", AUDIO_SERVICE)) { audioManager.Call("setStreamVolume", STREAM_MUSIC, (int)current, 0); } } }