Дифференциальная остановка и удаление с помощью приложения AudioHandler for Flutter от audio_service

Just_audio AudioPlayer позволяет как останавливать, так и удалять:

      _player.stop();
_player.dispose();

Вы используете, когда вы все еще можете захотеть снова начать играть в будущем, тогда как когда вы полностью закончили.

Моя проблема в том, что audio_service AudioHandler, который обертывает just_audio AudioPlayer, имеет только stopметод. Здесь нет dispose.

Правильный ли способ сделать это - добавить настраиваемое действие?

      @override
Future customAction(String name, Map<String, dynamic>? arguments) async {
  if (name == 'dispose') {
    await _player.dispose();
    await super.stop();
  }
}

И назовите это так:

      myAudioHandler.customAction('dispose', null);

1 ответ

Assuming 0.18.0 onward, yes that is correct. As a slight improvement, you can also optionally wrap the custom action call in an extension method:

      extension AudioHandlerExtension on AudioHandler {
  Future<void> dispose() => customAction('dispose');
}

Then you can call it like this:

      await myAudioHandler.dispose();

There is another approach which cheats a little, and that is: rather than using a custom action, you can just add a method directly to your handler class:

      class MyAudioHandler extends BaseAudioHandler {
  ...

  Future<void> dispose() => _player.dispose();
}

Then retain a typed reference to your instance so that you can later call the method directly on it:

      myAudioHandler = await AudioService.init(
  builder: () => MyAudioHandler(),
}
...
await myAudioHandler.dispose();

You just need to be aware of the following limitations:

  • If you have multiple audio handler classes that are composed together, this dispose method will not propagate through all of them, the method will only be available in the MyAudioHandler class.
  • This will only work if you're calling from the same isolate.
  • If your app is designed to respond to custom actions from another process, this approach won't support that.

This approach might be good enough for simple apps that don't use composition, multiple isolates or IPC.

Другие вопросы по тегам