.NET Maui Android平台播放系统通知提示音实现方法
在.NET Maui中播放系统提示音的方法
方式一:依赖服务实现跨平台播放
通过依赖服务调用各平台原生API播放系统默认通知提示音,是.NET Maui跨平台场景的推荐方案。
- 定义共享接口
在共享项目中创建播放系统声音的接口:
public interface ISystemSoundPlayer { void PlayNotificationSound(); }
- Android平台实现
在Android平台项目中实现该接口,调用系统RingtoneManager获取并播放默认通知铃声:
[assembly: Dependency(typeof(SystemSoundPlayer_Android))] namespace YourAppName.Platforms.Android { public class SystemSoundPlayer_Android : ISystemSoundPlayer { public void PlayNotificationSound() { var notificationUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); var ringtone = RingtoneManager.GetRingtone(Android.App.Application.Context, notificationUri); ringtone?.Play(); } } }
注意:若在Android 12及以上版本遇到播放失败,需在
AndroidManifest.xml中添加权限:<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
- iOS平台实现(可选)
如果需要支持iOS,在iOS平台项目中实现接口,调用系统音效API:
[assembly: Dependency(typeof(SystemSoundPlayer_iOS))] namespace YourAppName.Platforms.iOS { public class SystemSoundPlayer_iOS : ISystemSoundPlayer { public void PlayNotificationSound() { var notificationSound = AudioToolbox.SystemSound.FromFile("/System/Library/Audio/UISounds/notification_sound.mp3"); notificationSound.PlaySystemSound(); } } }
- 在共享代码中调用
在需要播放提示音的地方,通过依赖服务获取实例并调用方法:
var soundPlayer = DependencyService.Get<ISystemSoundPlayer>(); soundPlayer?.PlayNotificationSound();
方式二:Android平台直接调用(仅Android场景)
如果应用仅需支持Android,可直接在Android项目代码中调用原生API,无需依赖服务:
var notificationUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); var ringtone = RingtoneManager.GetRingtone(Android.App.Application.Context, notificationUri); ringtone?.Play();
内容的提问来源于stack exchange,提问作者Dryzler
相关产品推荐
相关产品推荐

