12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- 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()
- {
- }
- /// <summary>
- /// 获取Android系统音量值
- /// </summary>
- /// <returns></returns>
- public int GetMusicVolume()
- {
- AndroidJavaObject context = new AndroidJavaClass("com.unity3d.player.UnityPlayer").
- GetStatic<AndroidJavaObject>("currentActivity");
- using (AndroidJavaObject audioManager = context.Call<AndroidJavaObject>("getSystemService", AUDIO_SERVICE))
- {
- max = audioManager.Call<int>("getStreamMaxVolume", STREAM_MUSIC);
- current = audioManager.Call<int>("getStreamVolume", STREAM_MUSIC);
- Debug.Log("当前音量:" + current);
- }
- return current;
- }
- private void Update()
- {
- // text.text = GetMusicVolume().ToString();
- }
- /// <summary>
- /// 设置Android系统音量值
- /// </summary>
- /// <param name="volume"></param>
- public void SetMusicVolume(int volume)
- {
- current -= volume;
- AndroidJavaObject context = new AndroidJavaClass("com.unity3d.player.UnityPlayer").
- GetStatic<AndroidJavaObject>("currentActivity");
- using (AndroidJavaObject audioManager = context.Call<AndroidJavaObject>("getSystemService", AUDIO_SERVICE))
- {
- audioManager.Call("setStreamVolume", STREAM_MUSIC, (int)current, 0);
- }
- }
- /// <summary>
- /// 设置Android系统音量值
- /// </summary>
- /// <param name="volume"></param>
- public void SetMusicVolumeAdd(int volume)
- {
- current += volume;
- AndroidJavaObject context = new AndroidJavaClass("com.unity3d.player.UnityPlayer").
- GetStatic<AndroidJavaObject>("currentActivity");
- using (AndroidJavaObject audioManager = context.Call<AndroidJavaObject>("getSystemService", AUDIO_SERVICE))
- {
- audioManager.Call("setStreamVolume", STREAM_MUSIC, (int)current, 0);
- }
- }
- }
|