skip to Main Content

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


  1. Chosen as BEST ANSWER

    ok so i created a method which working fine

    String portName = 'audio_isolate';
    
    fcmBackgroundHandler() async {
     ReceivePort receiver = ReceivePort();
     IsolateNameServer.registerPortWithName(receiver.sendPort, portName);
    
     receiver.listen((message) async {
       debugPrint('oyeah play $message');
      if (message == "play") {
        await FlutterRingtonePlayer().play(
          looping: true,
          fromAsset: 'assets/ringtone.mp3',
        );
      }
      if (message == "stop") {
         await FlutterRingtonePlayer().stop();
      }
     });
     }
    

    and just play stop it using

     IsolateNameServer.lookupPortByName(portName)?.send("play");
    

    and

     IsolateNameServer.lookupPortByName(portName)?.send("stop");
    

    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


  2. The isolate seems fine. The issue might be the sound.
    You should first play your audio instead of resuming it.

    Try that:

    if (message == 'play') {
            debugPrint('Playing audio...');
            if (audioPlayer.state == PlayerState.paused ||
                audioPlayer.state == PlayerState.stopped) {
              await audioPlayer.resume();
            } else {
              await audioPlayer.play(AssetSource('ringtone.mp3'));
            }
          }
    

    heads up:

    1. ensure your assets are set correctly inside the pubspec.yaml file
    2. During my tests the hot restart made it stop working. it might be my messed up environment but worth checking stop debugging and try again.
    3. I ran it on a real Android device. Not sure if it would work on an emulator.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search