Search code examples
iosflutterdartaudionotifications

How to play audio in flutter ios app when app is killed?


In my app I am trying to play a specific sound when new notification comes. It is working fine in android. But in IOS if the app is in background it will work. If the app is killed it will play default notification sound.

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();
  if(message.data['navigate_to']=='idea'){
    FlutterRingtonePlayer.play(fromAsset: "assets/alerts/trade.mp3",
      ios : IosSounds.electronic,
      asAlarm: true,);
  }
}

I am using flutter_ringtone_player for playing audio. Also tried with just_audio, assets_audio_player, audioPlayers. Everything is working when the app is in background only not when killed. (only in IOS)


Solution

  • Notification sounds work slightly different on iOS than on Android. While on Android, you can play the sound yourself, on iOS this feature is limited by the operating system.

    If you want to provide a different sound than the default one, you will have to specify that in the push notification payload, i.e. on the server side. An example on how to specify this sound property in Firebase messaging can be found in this question.

    More detailed information about these limitations can be found in Apple's documentation of UNNotificationSound.

    • The sound file has to be already present on the device
    • The sound file can be max. 30s seconds long