Canardoux / flutter_sound

Flutter plugin for sound. Audio recorder and player.
Mozilla Public License 2.0
874 stars 569 forks source link

[HELP] Error when execute FlutterSoundRecord in Isolate.spawn() #586

Open mahdidham opened 3 years ago

mahdidham commented 3 years ago

After i test it to run record.OpenAudioSession() this error happened.

E/flutter: [ERROR:flutter/runtime/dart_isolate.cc(882)] Unhandled exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized. If you're running an application and need to access the binary messenger before runApp() has been called (for example, during plugin initialization), then you need to explicitly call the WidgetsFlutterBinding.ensureInitialized() first. If you're running a test, you can call the TestWidgetsFlutterBinding.ensureInitialized() as the first line in your test's main() method to initialize the binding.

The error said that to implement WidgetsFlutterBinding.ensureInitialized() but I have already create it on the main(). I don't have any documentation to explain why this cannot run at flutter isolate. I am sure if there is some explanation

here's the code

void _isolateHandler() async {
    _receivePort = ReceivePort();
    _receivePort.listen(_handleMessage);
    print('isolate: start spawn');
    _isolate = await Isolate.spawn(_isolateRecord, _receivePort.sendPort);
  }

static void _isolateRecord(dynamic message) {
    SendPort sendPort;
    final receivePort = ReceivePort();
    print('isolate: thread isolate for record here');
    if (_recorder == null) {
      _recorder = FlutterSoundRecorder();
    }
    receivePort.listen((message) async {
      /*
        todo: receiving message from main thread.
         listen if main want to start record or stop record
       */
      if (message is Recordstate) {
        if (_recorder == null) {
          _recorder = FlutterSoundRecorder();
        }
        switch (message) {
          case Recordstate.record:
            // TODO: create new class for record or for audiorecorder worker
            await recording();
            break;
          case Recordstate.pause:
            // do pause record
            break;
          case Recordstate.stop:
            // do stop record
            await stopping();
            break;
        }
      }
    });

    if (message is SendPort) {
      print('get port from main thread');
      // TODO: resend send port to make sure isolate ready
      sendPort = message;
      sendPort.send(receivePort.sendPort);
      return;
    }
  }
Larpoux commented 3 years ago

I cannot help you very much. I never used Isolates. Is your problem with Android or iOS ?

Android uses "Services". Perhaps the problem is somewhere here.

github-actions[bot] commented 10 months ago

This issue is stale because it has been open 90 days with no activity. Leave a comment or this will be closed in 7 days.