Search code examples
flutterflutter-local-notification

Flutter schedule notification using recorded audio


Currently I am building an app that requires me to implement a functionality to record audio and use the recorded audio as the sound for a local notification.

I have already set up the notifications using flutter_local_notifications, but as far as I am aware, with this plugin you can only specify sounds that have been added to the resource folder before runtime.

This would look like this:

const String soundName = 'test_sound.mp3';

NotificationDetails(
      android: AndroidNotificationDetails(
        'channel id',
        'channel name',
        channelDescription: 'channel description',
        sound: RawResourceAndroidNotificationSound(soundName.split('.').first),
      ),
      iOS: DarwinNotificationDetails(),
    );

Is there a way to record audio files during runtime and use them right away when scheduling a new notification?


Solution

  • The solution is to record the audio file and save it to a location outside of the app. This could, for example, be:

    // Android
    var audio_directory = '/sdcard/Android/media/your_app_name/audio';
    
    // iOS
    final Directory dir = await getLibraryDirectory();
    var audio_directory = '${join(dir.path, 'Sounds')}/';
    

    Then use the file when scheduling a new notification like this:

    NotificationDetails(
          android: AndroidNotificationDetails(
            '1',
            '1',
            channelDescription: '1',
            importance: Importance.max,
            sound: UriAndroidNotificationSound(
                    'file:///sdcard/Android/media/your_app_name/$soundFile.wav',
                   ),
            playSound: vibrationOnly ? false : true,
          ),
          iOS: DarwinNotificationDetails(
                  sound: '$soundFile.aiff',
                  presentSound: true,
               ),
    );