buildPlayButton method

Widget buildPlayButton()

Build the play/pause button

Implementation

Widget buildPlayButton() {
  return MultiValueListenableBuilder(
    valueListenables: [
      _playerStateNotifier,
    ],
    builder: (context, values, _) {
      PlayerState? playerState = values.elementAt(0);

      IconData iconData = Icons.play_arrow;

      if (playerState == null ||
          playerState.processingState == ProcessingState.completed) {
        iconData = Icons.play_arrow;
      } else if (playerState.playing) {
        iconData = Icons.pause;
      } else {
        iconData = Icons.play_arrow;
      }

      return IconButton(
        icon: Icon(iconData, size: 24),
        onPressed: () async {
          final AudioSession session = await AudioSession.instance;
          await session.configure(
            const AudioSessionConfiguration(
              avAudioSessionCategory: AVAudioSessionCategory.playback,
              avAudioSessionCategoryOptions:
                  AVAudioSessionCategoryOptions.duckOthers,
              avAudioSessionMode: AVAudioSessionMode.defaultMode,
              avAudioSessionRouteSharingPolicy:
                  AVAudioSessionRouteSharingPolicy.defaultPolicy,
              avAudioSessionSetActiveOptions:
                  AVAudioSessionSetActiveOptions.none,
              androidAudioAttributes: AndroidAudioAttributes(
                contentType: AndroidAudioContentType.music,
                usage: AndroidAudioUsage.media,
              ),
              androidAudioFocusGainType:
                  AndroidAudioFocusGainType.gainTransientMayDuck,
              androidWillPauseWhenDucked: true,
            ),
          );

          session.becomingNoisyEventStream.listen((event) async {
            await _audioPlayer.pause();
            session.setActive(false);
          });

          if (playerState == null ||
              playerState.processingState == ProcessingState.completed) {
            await _audioPlayer.seek(Duration.zero);

            session.setActive(true);
            await _audioPlayer.play();
            session.setActive(false);
          } else if (playerState.playing) {
            await _audioPlayer.pause();
            session.setActive(false);
          } else {
            session.setActive(true);
            await _audioPlayer.play();
            session.setActive(false);
          }
        },
      );
    },
  );
}