using System;
using AVFoundation;
using Foundation;
using MediaPlayer;
using Shared;
using UIKit;
namespace com.hdl.on
{
public static class Volume
{
///
/// 声音变化事件
///
public static Action VolumeChange;
///
/// 设置当前音量
///
/// Volume.
public static int MusicVolume
{
set
{
if ((DateTime.Now - dateTime).TotalMilliseconds < 2000)
{
return;
}
foreach (var view in BaseViewController.MPVolumeView.Subviews)
{
if (view.GetType().Name == "UISlider")
{
(view as UISlider).SetValue((float)Math.Round(value / 100.0f, 2, MidpointRounding.AwayFromZero), false);
beforeVolume = (view as UISlider).Value;
//Shared.HDLUtils.WriteLine("接收到更新音量:" + (float)Math.Round(value / 100.0f, 2, MidpointRounding.AwayFromZero) + " " + beforeVolume);
break;
}
}
}
}
static System.DateTime dateTime = DateTime.MinValue;
///
/// 之前的音量
///
static float beforeVolume;
public static void Init()
{
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("AVSystemController_SystemVolumeDidChangeNotification"),
(obj) =>
{
//如果应用进入后台,不执行音量变化
if (UIApplication.SharedApplication.ApplicationState != UIApplicationState.Active || "Audio/Video" != obj.UserInfo.ObjectForKey(new NSString("AVSystemController_AudioCategoryNotificationParameter")).ToString())
{
return;
}
//Shared.HDLUtils.WriteLine("接收到音量变化事件");
dateTime = DateTime.Now;
var tempValue = obj.UserInfo.ObjectForKey(new NSString("AVSystemController_AudioVolumeNotificationParameter"));
if (tempValue == null)
{
return;
}
try
{
//有时转换失败,可能有时值有问题
var volume = 100 * float.Parse(tempValue.ToString());
volume = (float)Math.Round(volume, 2, MidpointRounding.AwayFromZero);
//Shared.HDLUtils.WriteLine("音量变化事件:" + volume + " " + beforeVolume * 100);
if (VolumeChange != null && beforeVolume * 100 != volume)
{
VolumeChange((int)volume);
}
}
catch { }
});
}
}
}