Search code examples
flutteraudio

Flutter - How to know when an audio starts playing? (without user action)


I have an app that starts to play audio files automatically on a specific screen.

I want to display relevant message on the screen according to the playing audio.

The problem is that every time I load the audio it takes different time for it to load, and therefore I don't know when to start displaying the message.

I want to know when the audio starts to play (no user input for that).

Code:

Future<int> _playAudio({required String url}) async {
    final playPosition = (_position != null &&
            _duration != null &&
            _position!.inMilliseconds > 0 &&
            _position!.inMilliseconds < _duration!.inMilliseconds)
        ? _position
        : null;
    final result = await _audioPlayer.play(url, position: playPosition);
    if (result == 1) {
      setState(() => _playerState = PlayerState.PLAYING);
      displayMessage();
    }
    _audioPlayer.setPlaybackRate();
    return result;
  }

Thanks!


Solution

  • You can listen to PlayerState event of _audioPlayer as documented here State Event

    _audioPlayer.onPlayerStateChanged.listen((PlayerState s) => {
      print('Current player state: $s');
      setState(() => _playerState = s);
    });