iOS11及以上版本Xamarin.iOS音频静音实现方案咨询
Hey there! I’ve run into this exact problem while building iOS audio players with XamarinMediaManager, so let me share the proper solutions to replace that deprecated Volume property for muting via volume control.
Starting with iOS 10, Apple deprecated the MPMusicPlayerController.Volume property because they want apps to control their own audio sessions instead of modifying the system-wide music player volume. The best fix here is to switch your XamarinMediaManager setup to use AVPlayer under the hood, which lets you safely control volume for your app's audio.
Here's how to implement it:
Configure XamarinMediaManager to use AVPlayer
When initializing the media manager, set it to use the AVPlayer-based audio player implementation:// Place this in your app's initialization code (like AppDelegate.cs) CrossMediaManager.Current.Init(new MediaManagerConfiguration { AudioPlayerType = typeof(AudioPlayerImplementation) });Implement Mute/Unmute with AVPlayer Volume
Save the current volume state, then toggle the AVPlayer's volume between 0 (muted) and the saved value when the button is tapped:// Store the previous volume to restore later private float _lastVolume = 1.0f; // Mute button click handler private void OnMuteButtonClicked(object sender, EventArgs e) { var audioPlayer = CrossMediaManager.Current.AudioPlayer as AudioPlayerImplementation; if (audioPlayer == null) return; if (audioPlayer.Player.Volume > 0) { // Save current volume and mute _lastVolume = audioPlayer.Player.Volume; audioPlayer.Player.Volume = 0; } else { // Restore previous volume audioPlayer.Player.Volume = _lastVolume; } }
If you absolutely need to modify the system-wide volume (though Apple discourages this, as it affects all apps), you can use a hidden MPVolumeView to adjust the system volume. Note that this relies on accessing private UI elements and might break in future iOS versions or get rejected by the App Store:
private void SetSystemVolumeToMute() { // Create a hidden MPVolumeView var volumeView = new MPVolumeView(); volumeView.Hidden = true; // Add it to your view hierarchy (required for it to work) View.AddSubview(volumeView); // Find the volume slider and set it to 0 foreach (var subview in volumeView.Subviews) { if (subview is UISlider volumeSlider) { volumeSlider.Value = 0; break; } } }
Important: This method is not reliable long-term. Apple restricts direct system volume changes, so using AVPlayer to control your app's own audio is always the safer, compliant choice.
内容的提问来源于stack exchange,提问作者user5699258

