Flutter本地通知自定义声音无法正常工作(路径问题)

12

var androidPlatformChannelSpecifics =
                    new AndroidNotificationDetails(
                        "$id",
                        not.columnValue + not.deveui,
                        not.columnValue + not.deveui,
                        sound: "@raw/alarm",
                        importance: Importance.Max,
                        priority: Priority.High);

事实上,它仍然使用默认的系统声音。

如果我放置@raw/alarm.mp3,我会得到以下异常:Unhandled Exception: PlatformException(INVALID_SOUND, The resource %s could not be found. Please make sure it has been added as a raw resource to your Android head project., null)

注意:声音:RawResourceAndroidNotificationSound('alarm'),已解决

3个回答

23

感谢sunnyque提供了出色的解决方案,但是以下是我将其实现到我的FCM上的方法:

首先:你需要设置"channel_id","playSound: true", "sound: RawResourceAndroidNotificationSound('yourmp3files.mp3')"在flutter_local_notification中添加特定通道

Future displayNotification(Map<String, dynamic> message) async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      'you_can_name_it_whatever',
      'flutterfcm',
      'flutterfcm',
      playSound: true,
      sound: RawResourceAndroidNotificationSound('yourmp3files.mp3'),
      importance: Importance.max,
      priority: Priority.high,
    );

然后,将mp3文件添加到res/raw/yourmp3files.mp3 添加mp3

之后,需要在res/raw/keep.xml中添加keep.xml以将yourmp3files.mp3包含在构建中 keep.xml

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:keep="@raw/yourmp3files"
    />

你做完了,现在可以在应用程序中测试FCM自定义声音,执行以下操作:

卸载上一个版本

运行flutter clean命令

运行flutter pub get命令

运行flutter build apk命令

运行flutter run --release命令

完成了,如果可行请告诉我,呵呵

希望这对未来的某个人有所帮助。


3
在RawResourceAndroidNotificationSound中移除“.mp3”解决了我的问题。 - ymerdrengene
我遇到了同样的错误,通过添加keep.xml文件来解决了问题,但是通知没有声音(尽管震动是有效的)。可能的原因是什么? - Hemabh
Flutter能否从该目录播放声音文件? - Muhammad Qasim
移除“.mp3”对我也起作用 像这样 -> 声音:RawResourceAndroidNotificationSound('yourmp3files'), - Rasel Khan
你救了我的一天,亲爱的先生,我向你致敬。 - undefined
显示剩余2条评论

4

为了完成之前提供的有用帮助,请不要忘记在应用程序创建之前修改您的频道ID,如果您的声音修改已经完成。我不知道为什么,但使用现有的频道时,声音不会被考虑在内(因此浪费了几个小时,希望这可以帮助其他人)。


这个答案将会拯救我们很多人 <3 - Anas Yousuf

4

您不需要在路径中添加“@raw/”,插件已经从中获取声音(根据插件源代码:FlutterLocalNotificationsPlugin.java函数retrieveSoundResourceUri),请将其删除。

还要检查声音文件是否已包含在构建中,例如通过在原始文件夹中创建keep.xml并使用以下内容:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:keep="@drawable/*,@raw/alarm" />

可能会有所帮助。

1
你提到包含keep.xml文件的建议解决了我一直面临的所有问题。谢谢! - fpsColton
@Synnyque 这个目录里的音频文件能否通过音频播放器播放? - Muhammad Qasim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接