Flutter中FlutterLocalNotificationsPlugin自定义通知声音无法播放问题求助
我最近在Flutter项目里用FlutterLocalNotificationsPlugin实现本地通知,想给通知添加自定义声音,已经把notification.mp3放到了android/app/src/main/res/raw目录里,也用RawResourceAndroidNotificationSound('notification')来引用,但自定义声音就是不播放,日志还提示找不到这个声音文件。下面是我的通知通道初始化代码片段:
static Future initLocalNotification({bool isScheduled = false}) async { final androidInit = AndroidInitializationSettings('@mipmap/ic_launcher'); final iosInit = DarwinInitializationSettings(); final initSetting = InitializationSettings(android: androidInit, iOS: iosInit); await _flutterLocalNotificationsPlugin.initialize(initSetting); log("inside initlocalNotification"); // Define default notification channels with custom sound AndroidNotificationChannel orderReceiveChannel = AndroidNotificationChannel( // 此处为未完成的代码片段 ... ); }
想请教各位开发者,我这哪里出问题了?有没有可行的排查和解决方法?
可能的排查方向和解决方案:
检查文件命名与格式合规性
Android资源文件命名有严格规则:只能用小写字母、数字、下划线和点,不能包含空格或大写字母。确认你的notification.mp3完全符合要求,同时确保文件是标准MP3格式(比特率、时长不要过于极端,比如避免超过30秒的长音频),可以换一个已知可用的短音频文件测试。确认资源文件被正确打包
有时候文件虽然放在了正确目录,但可能没被Android Studio识别为编译资源:- 执行
flutter clean清理缓存,再运行flutter pub get后重新启动项目; - 直接打开Android模块(右键项目中android文件夹,选择
Open in Android Studio),检查res/raw目录下的notification.mp3是否显示为音频图标(如果是普通文件图标,说明未被识别为资源)。
- 执行
确保通知通道配置正确
Android O及以上版本中,通知声音必须在创建通道时指定,且通道创建后无法修改核心属性(包括声音)。完整的通道创建代码应该是这样的:AndroidNotificationChannel orderReceiveChannel = AndroidNotificationChannel( 'order_receive_channel_id', // 唯一通道ID '订单接收通知', // 通道名称 description: '用于接收新订单的通知', // 通道描述 importance: Importance.high, sound: RawResourceAndroidNotificationSound('notification'), // 指定自定义声音 playSound: true, ); // 必须执行创建通道的操作 await _flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(orderReceiveChannel);如果你之前创建过无自定义声音的同名通道,需要先卸载APP再重新安装(通道属性无法动态修改)。
发送通知时指定对应通道ID
发送通知的AndroidNotificationDetails必须和创建的通道ID一致,否则会使用默认通道(默认通道用系统声音):final androidDetails = AndroidNotificationDetails( 'order_receive_channel_id', // 与创建的通道ID保持一致 '订单接收通知', channelDescription: '用于接收新订单的通知', importance: Importance.high, priority: Priority.high, sound: RawResourceAndroidNotificationSound('notification'), // 可重复指定确保生效 ); final notificationDetails = NotificationDetails(android: androidDetails); await _flutterLocalNotificationsPlugin.show( 0, '新订单提醒', '你有一个新的订单待处理', notificationDetails, );查看具体日志错误信息
如果日志提示类似Couldn't find resource raw/notification,基本可以定位是文件名错误、文件未被打包,或者通道配置未关联到该声音文件,可以针对性排查。
备注:内容来源于stack exchange,提问作者Satyam Jha

