Flutter中用Awesome Notifications实现系统/自定义通知音效的方法
Flutter Awesome Notifications 音效实现方案
1. 使用设备默认通知音效
要调用设备默认通知音效,只需不设置soundSource参数(或直接将其设为null),同时保持playSound: true即可。Awesome Notifications在未指定自定义音效时,会自动使用系统默认通知音。
修改后的初始化代码:
AwesomeNotifications().initialize( null, [ NotificationChannel( channelKey: 'key1', channelName: 'Recipedia', channelDescription: 'Testing Notification', defaultColor: const Color(0XFFff735c), ledColor: const Color(0XFFff735c), soundSource: null, // 移除或设为null即可启用默认音效 enableLights: true, enableVibration: true, playSound: true, ) ], );
2. 自定义音效的完整配置
你已将notification.mp3放入asset文件夹,还需完成以下步骤确保音效正常生效:
第一步:在pubspec.yaml中声明资源
必须在项目配置文件里注册音效资源,否则Flutter无法读取到文件:
flutter: assets: - assets/notification.mp3 - assets/OTP1.png # 同步注册你的通知大图资源
第二步:确认通知频道配置
你原有的初始化代码已经正确设置了soundSource: 'assets/notification.mp3',只要保持playSound: true,创建通知时会自动使用该频道指定的音效。如果需要给单个通知单独指定音效,也可以在NotificationContent中额外设置soundSource参数覆盖频道配置。
验证后的自定义音效初始化代码(配合pubspec配置即可正常使用):
AwesomeNotifications().initialize( null, [ NotificationChannel( channelKey: 'key1', channelName: 'Recipedia', channelDescription: 'Testing Notification', defaultColor: const Color(0XFFff735c), ledColor: const Color(0XFFff735c), soundSource: 'assets/notification.mp3', enableLights: true, enableVibration: true, playSound: true, ) ], );
额外注意事项
- 音效文件优先使用MP3格式,确保Android和iOS双端兼容
- Android端也可将音效文件放入
android/app/src/main/res/raw目录,此时soundSource设为'resource://raw/notification'(无需加文件后缀) - iOS端需将音效文件添加到Xcode项目资源列表中,保证打包时能正确包含
内容的提问来源于stack exchange,提问作者Mr Fin
相关产品推荐
相关产品推荐

