hi i want to implement an Isolate to play stop audio ringtone from assets
i have created isolate but don’t know why it is not working is anybody have any idea what i am missing here below is my sample code
void audioIsolateEntry() async {
final ReceivePort receivePort = ReceivePort();
IsolateNameServer.registerPortWithName(receivePort.sendPort, 'audio_isolate');
final audioPlayer = AudioPlayer();
receivePort.listen((message) async {
if (message == 'play') {
debugPrint('Playing audio...');
await audioPlayer.setSource(AssetSource('ringtone.mp3'));
await audioPlayer.resume();
} else if (message == 'pause') {
debugPrint('Pausing audio...');
await audioPlayer.pause();
} else if (message == 'stop') {
debugPrint('Stopping audio...');
await audioPlayer.stop();
}
});
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
void playAudio() {
final isolate = IsolateNameServer.lookupPortByName('audio_isolate');
debugPrint('play isolate $isolate');
if (isolate != null) {
debugPrint('playing $isolate');
isolate.send('play');
} else {
debugPrint('Isolate not found!');
}
}
void pauseAudio() async {
final isolate = await IsolateNameServer.lookupPortByName('audio_isolate');
if (isolate != null) {
isolate.send('pause');
} else {
debugPrint('Isolate not found!');
}
}
void stopAudio() async {
final isolate = await IsolateNameServer.lookupPortByName('audio_isolate');
if (isolate != null) {
isolate.send('stop');
} else {
debugPrint('Isolate not found!');
}
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
AudioPlayer? audioPlayer;
@override
void initState() {
super.initState();
register();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Audio Player'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children:[
ElevatedButton(
onPressed: () async {
playAudio();
},
child: const Text('Play'),
),
ElevatedButton(
onPressed: () {
stopAudio();
},
child: const Text('Stop'),
),
],
),
),
),
);
}
void register() {
audioIsolateEntry();
}
}
2
Answers
ok so i created a method which working fine
and just play stop it using
and
but what i see wrong with it is that when i use it inisde FCM background handler to play ringtone when get a notification is it take little bit more time to play so be careful to use it in backgroundhandler
The isolate seems fine. The issue might be the sound.
You should first play your audio instead of resuming it.
Try that:
heads up:
pubspec.yaml
file