Shebin PR
Shebin PR

Reputation: 145

How to add custom notification sound for firebase push notification - Flutter

I am currently using firebase push notifications for notifications. I need to customize the default sound.

I tried by "sound": "alert.mp3", instead of "sound": "default", but the sound I have given didn't trigger.

Upvotes: 3

Views: 18665

Answers (3)

Sambhav jain
Sambhav jain

Reputation: 2793

Custom notification in Flutter

Android setup

Firstly create an extra notification channel with

  // channel for default notifications
  const AndroidNotificationChannel channel = AndroidNotificationChannel(
      'wave_remote_notifications', // id
      'Wave messages and updates', // title
      description: 'Primary channel for notifications and messages in wave app',
      importance: Importance.max,
    );
   
   // channel for custom sound  
   const AndroidNotificationChannel channelAudio = AndroidNotificationChannel(
      'wave_remote_notifications_priority', // id
      'Wave messages and updates on priority', // title
      description: 'Primary channel for notifications and messages in wave app',
      sound: RawResourceAndroidNotificationSound('mario'),
      importance: Importance.max,
    );
    
    
    // if you use flutter_local_notification 
    
      await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);
        
    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channelAudio);

you can see we have added RawResourceAndroidNotificationSound('mario')

Now add mp3/wav file into res/raw/yourmp3files.mp3

now notification will work but only for debug mode as this file you added will not be included in release mode

So after that you need to add keep.xml inside res/raw/keep.xml to include yourmp3files.mp3 into build keep.xml

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

iOS setup

You have to add the sound into XCode. You can just drag and drop the audio file (in .caf or .wav supported format ) into the root directory (usually called Runner for Flutter) in XCode

That's all

FCM Payload

final step

{
    "to": "f31vmSf8Qy2N57_33C9cf3:APA91bHBaz7yyRrKQTr_25mLNK2OVlBjdMqM8ux8kQwaeQcsXE6XnOhio7Tp5-CABTFTSbV1vBqqfIVj9Qd9eUdqNi9oojq8FdOWI-l1CU9Xw16-Xb4ZHVTycOM7nIRudIAmMkU6fjbm",
    // "collapse_key": "type_a",
    "priority": "high",
    "notification": {
        "title": "New visitor request",
        "body": "Answer to accept",
        "sound": "mario.wav",
        "android_channel_id": "wave_remote_notifications_priority"
    },
    "data": {
        "title": "New visitor request",
        "body": "Answer to accept ",
        "sound": "mario",
    },
    "content_available": true,
    "apns": {
        "payload": {
            "aps": {
                "mutable-content": 1,
                "content-available": 1
            }
        }
    }
}

All set now all should work

Upvotes: 0

Punnoose K Thomas
Punnoose K Thomas

Reputation: 1

For this, you have two approaches. Both approaches require that you have a file with any name ("notification.wav" for this example) in your assets folder and that you have declared this file/folder in your pubspec.yaml file.

Approach 1 : First, open the android part of the project in Android Studio and create a raw resource that specifies "notification.wav" as a resource. Then, when specifying AndroidNotificationDetails for firebase notifications, declare the 'playsound' and 'sound' parameter as follows :

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,
  ]
);

The 'sound' parameter must be sent from backend in case of background notifications.

Approach 2 : This approach uses the AudioPlayer class to play the asset audio when the notification is shown. This is implemented as a media audio rather than as a notification audio, so it will depend on the media volume of the device. I'll provide a sample that rings only when the phone is not in silent or vibrate, and forces the media volume to be maxed out using the volume_controller plugin.

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();
  }
}

This function can be declared inside the FireBase class to use for foreground notification, but to use in the background, it must either be defined outside the class as a root function with the @pragma tag, or the content code must be used within the background handler function that's declared with the @pragma tag. If you wish to stop this alert when the notification is clicked instead of running for entire 5 seconds, you can assign the audio player to a global variable and then user the global variable to stop, release and dispose the player when notification is clicked.

Upvotes: 0

Ahmed Elhenidy
Ahmed Elhenidy

Reputation: 342

check out the solution here to know how to specify a custom sound for both android and iOS

Upvotes: 2

Related Questions