You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Maui Android平台播放系统通知提示音实现方法

在.NET Maui中播放系统提示音的方法

方式一:依赖服务实现跨平台播放

通过依赖服务调用各平台原生API播放系统默认通知提示音,是.NET Maui跨平台场景的推荐方案。

  1. 定义共享接口
    在共享项目中创建播放系统声音的接口:
public interface ISystemSoundPlayer
{
    void PlayNotificationSound();
}
  1. 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" />
  1. 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();
        }
    }
}
  1. 在共享代码中调用
    在需要播放提示音的地方,通过依赖服务获取实例并调用方法:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 17:49:59