So this morning casually strolling through the wishlist section I saw a post by Shuvam Kar wanting Custom Sound Notification and much to my surprise it had many upvotes (and I legit thought that was a super low hanging fruit). So I decided to fix that for the community, one less feature Inactive Member have to worry about. So here it goes a VERY simple custom action that takes in ANY sound URL and plays you the sound as a notification. Before we enter code some warning:
WARNING TO 'CREATIVE' DEVELOPERS!🚨🚨 :
The package saves the sound in local buffer memory so that it can play the sound ASAP (no lag) on-demand. That means, DO NOT EVER EVER use this custom action to play regular music (uno as an offline music player), your app performance would lag as it will hug up all memory space. It is strictly for playing SHORT AUDIO NOTIFICATIONS (<15 seconds) 🎶
We are gonna be using this package SoundPool
STEP 1: Create a custom action, with NO RETURN VALUE call it playNotificationSound
STEP2: Add these two dependencies to your action : soundpool: ^2.2.0
soundpool_web: ^2.2.0
STEP 3: Add a parameter to the action called alertSoundUrl (type String, non-Nullable).
Now add this code below just replace everything below the FF imports, then save and compile!
import 'package:http/http.dart' as http;
import 'package:soundpool/soundpool.dart';
import 'package:flutter/services.dart';
Future<void> playNotificationSound(String alertSoundUrl) async {
Soundpool pool = Soundpool(streamType: StreamType.notification);
// Fetch sound tune from the URL
final response = await http.get(Uri.parse(alertSoundUrl));
if (response.statusCode == 200) {
// Convert to ByteData
ByteData soundData =
ByteData.sublistView(Uint8List.fromList(response.bodyBytes));
// Load the sound into the pool
int soundId = await pool.load(soundData);
// Play the sound
int streamId = await pool.play(soundId);
// Release the pool afterwards
pool.release();
} else {
print('Failed to load sound.');
}
}
And that's IT!! Amazing human, you have implemented custom sound notifications in your app.