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