fluttericecastjust-audioaudio-service

How to combine flutter audio_service and icymetadata streambuilder?


I am using Ryan Heise just audio and audio service flutter packages for Radio player app. Started out using AudioPlayer() in main.dart with a StreamBuilder listening to player.icymetadatastream and controlbuttons.dart with a stream builder listening to the playbackstate for showing play/pause controls. This works fine.

Now added audio_service package for background audio and iOS control center, etc. In main.dart we initialise AudioService with an Audiohandler. The controlbuttons.dart works when using a StreamBuilder on audiohandler.playbackstate instead of player.playerStateStream.

Can someone point me in the right direction for the metadata? The player is now encapsulated in the audiohandler.dart so I cannot reference it in my StreamBuilder in main.dart listening to the icymetadatastream. How should this be done? Also how to update the audio service with icymetadata changes? Is this supposed to be done with a mediaItem?


Solution

  • The simplest way is to add a getter for the stream to your handler:

    class MyAudioHandler extends BaseAudioHandler {
      AudioPlayer _player;
      ...
    
      Stream<IcyMetadata?> get icyMetadata => _player.icyMetadataStream;
    }
    

    Then in the main part of your app, you can reference this handler and its stream:

    myAudioHandler = await AudioService.init(builder: () => MyAudioHandler());
    
    ...
    
    MyAudioHandler.icyMetadata.listen((data) {
      ...
    });
    

    Another way, instead of defining an ordinary getter, is to define a custom action that returns the stream (via customAction). You might choose to do this if you are using composite audio handlers (e.g. SwitchAudioHandler). For more information on how to define a custom action, refer to the audio_service/example/lib/example_multiple_handlers.dart file in the official repository.