我目前正在使用 firebase 推送通知进行通知。我需要自定义默认声音。
我尝试使用“sound”:“alert.mp3”,而不是“sound”:“default”,但我给出的声音没有触发。
查看解决方案此处了解如何为 Android 和 iOS 指定自定义声音
为此,您有两种方法。这两种方法都要求您的资产文件夹中有一个具有任意名称的文件(本例中为“notification.wav”),并且您已在 pubspec.yaml 文件中声明了此文件/文件夹。
方法一: 首先,在 Android Studio 中打开项目的 android 部分,并创建一个原始资源,将“notification.wav”指定为资源。然后,在为 firebase 通知指定 AndroidNotificationDetails 时,声明 'playsound' 和 'sound' 参数,如下所示:
AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails(
"notification_id",
"notification channel name",
channelDescription: "notification channel description",
icon: "@mipmap/ic_launcher",
playSound: true,
sound: RawResourceAndroidNotificationSound("notification.wav"),
actions: [
accept_button,
]
);
如果有后台通知,必须从后端发送“声音”参数。
方法2: 此方法使用 AudioPlayer 类在显示通知时播放资产音频。这是作为媒体音频而不是通知音频实现的,因此它将取决于设备的媒体音量。我将提供一个仅在手机未处于静音或振动状态时响起的示例,并使用 volume_controller 插件强制媒体音量达到最大。
void audio_player_start() async {
var ringer_mode = await SoundMode.ringerModeStatus;
if(ringer_mode.name=="normal") {
VolumeController().maxVolume(showSystemUI: false);
AudioPlayer player = AudioPlayer(playerId: "customNotificationPlayer");
await player.setVolume(1.0);
player.play(AssetSource(Paths().MUSIC_FOLDER+"notification.wav"));
await Future.delayed(Duration(seconds: 10));
await player.stop();
await player.release();
await player.dispose();
}
}
此函数可以在 FireBase 类内部声明以用于前台通知,但要在后台使用,它必须在类外部定义为带有 @pragma 标记的根函数,或者内容代码必须在使用 @pragma 标记声明的后台处理函数。如果您希望在单击通知时停止此警报而不是运行整个 5 秒,您可以将音频播放器分配给全局变量,然后使用全局变量在单击通知时停止、释放和处置播放器。