How to send data to AudioServiceTask class which extends BackgroundAudioTask from UI

Well, I'm stuck on this problem. I have a code for audioservice (audioplayer.dart) which takes a queue to play. I'm getting the queue from playlist.dart in audioplayer.dart using ModalRoute and save in a global variable queue. Then, I initialize the AudioPlayerService. Now everything till here is fine but inside the AudioPlayerTask class which extends BackgroundAudioTask, when I try to access the variable (inside onStart) it comes out to be an empty list. I don't know where the problem is and I'm not very much familier with the BackgroundAudioTask class. Here's how it looks like:

import .....

List<MediaItem> queue = [];

class TempScreen extends StatefulWidget {
  @override
  _TempScreenState createState() => _TempScreenState();
}

class _TempScreenState extends State<TempScreen> {
      @override
      Widget build(BuildContext context) {
        queue = ModalRoute.of(context).settings.arguments;
        // NOW HERE THE QUEUE IS FINE
        return Container(.....all ui code);
        }

    // I'm using this button to start the service
    audioPlayerButton() {
    AudioService.start(
      backgroundTaskEntrypoint: _audioPlayerTaskEntrypoint,
      androidNotificationChannelName: 'Audio Service Demo',
      androidNotificationColor: 0xFF2196f3,
      androidNotificationIcon: 'mipmap/ic_launcher',
      androidEnableQueue: true,
    );
    AudioService.updateQueue(queue);
    print('updated queue at the start');
    print('queue now is $queue');
    AudioService.setRepeatMode(AudioServiceRepeatMode.none);
    AudioService.setShuffleMode(AudioServiceShuffleMode.none);
    AudioService.play();
  }
      }
    

void _audioPlayerTaskEntrypoint() async {
  AudioServiceBackground.run(() => AudioPlayerTask());
}

class AudioPlayerTask extends BackgroundAudioTask {
  AudioPlayer _player = AudioPlayer();
  Seeker _seeker;
  StreamSubscription<PlaybackEvent> _eventSubscription;
  String kUrl = '';
  String key = "38346591";
  String decrypt = "";
  String preferredQuality = '320';

  int get index => _player.currentIndex == null ? 0 : _player.currentIndex;
  MediaItem get mediaItem => index == null ? queue[0] : queue[index];

  // This is just a function i'm using to get song URLs
  fetchSongUrl(songId) async {
    print('starting fetching url');
    String songUrl =
        "https://www.jiosaavn.com/api.php?app_version=5.18.3&api_version=4&readable_version=5.18.3&v=79&_format=json&__call=song.getDetails&pids=" +
            songId;
    var res = await get(songUrl, headers: {"Accept": "application/json"});
    var resEdited = (res.body).split("-->");
    var getMain = jsonDecode(resEdited[1]);
    kUrl = await DesPlugin.decrypt(
        key, getMain[songId]["more_info"]["encrypted_media_url"]);
    kUrl = kUrl.replaceAll('96', '$preferredQuality');
    print('fetched url');
    return kUrl;
  }

  @override
  Future<void> onStart(Map<String, dynamic> params) async {
    print('inside onStart of audioPlayertask');
    print('queue now is $queue');
    // NOW HERE QUEUE COMES OUT TO BE AN EMPTY LIST
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration.speech());

    if (queue.length == 0) {
      print('queue is found to be null.........');
    }
    _player.currentIndexStream.listen((index) {
      if (index != null) AudioServiceBackground.setMediaItem(queue[index]);
    });
    // Propagate all events from the audio player to AudioService clients.
    _eventSubscription = _player.playbackEventStream.listen((event) {
      _broadcastState();
    });
    // Special processing for state transitions.
    _player.processingStateStream.listen((state) {
      switch (state) {
        case ProcessingState.completed:
          AudioService.currentMediaItem != queue.last
              ? AudioService.skipToNext()
              : AudioService.stop();
          break;
        case ProcessingState.ready:
          break;
        default:
          break;
      }
    });

    // Load and broadcast the queue
    print('queue is');
    print(queue);
    print('Index is $index');
    print('MediaItem is');
    print(queue[index]);
    try {
      if (queue[index].extras == null) {
        queue[index] = queue[index].copyWith(extras: {
          'URL': await fetchSongUrl(queue[index].id),
        });
      }

      await AudioServiceBackground.setQueue(queue);
      await _player.setUrl(queue[index].extras['URL']);
      onPlay();
    } catch (e) {
      print("Error: $e");
      onStop();
    }
  }

  @override
  Future<void> onSkipToQueueItem(String mediaId) async {
    // Then default implementations of onSkipToNext and onSkipToPrevious will
    // delegate to this method.
    final newIndex = queue.indexWhere((item) => item.id == mediaId);
    if (newIndex == -1) return;
    _player.pause();
    if (queue[newIndex].extras == null) {
      queue[newIndex] = queue[newIndex].copyWith(extras: {
        'URL': await fetchSongUrl(queue[newIndex].id),
      });
      await AudioServiceBackground.setQueue(queue);
      // AudioService.updateQueue(queue);
    }
    await _player.setUrl(queue[newIndex].extras['URL']);
    _player.play();
    await AudioServiceBackground.setMediaItem(queue[newIndex]);
  }

  @override
  Future<void> onUpdateQueue(List<MediaItem> queue) {
    AudioServiceBackground.setQueue(queue = queue);
    return super.onUpdateQueue(queue);
  }

  @override
  Future<void> onPlay() => _player.play();

  @override
  Future<void> onPause() => _player.pause();

  @override
  Future<void> onSeekTo(Duration position) => _player.seek(position);

  @override
  Future<void> onFastForward() => _seekRelative(fastForwardInterval);

  @override
  Future<void> onRewind() => _seekRelative(-rewindInterval);

  @override
  Future<void> onSeekForward(bool begin) async => _seekContinuously(begin, 1);

  @override
  Future<void> onSeekBackward(bool begin) async => _seekContinuously(begin, -1);

  @override
  Future<void> onStop() async {
    await _player.dispose();
    _eventSubscription.cancel();

    await _broadcastState();
    // Shut down this task
    await super.onStop();
  }

  Future<void> _seekRelative(Duration offset) async {
    var newPosition = _player.position + offset;
    // Make sure we don't jump out of bounds.
    if (newPosition < Duration.zero) newPosition = Duration.zero;
    if (newPosition > mediaItem.duration) newPosition = mediaItem.duration;
    // Perform the jump via a seek.
    await _player.seek(newPosition);
  }

  void _seekContinuously(bool begin, int direction) {
    _seeker?.stop();
    if (begin) {
      _seeker = Seeker(_player, Duration(seconds: 10 * direction),
          Duration(seconds: 1), mediaItem)
        ..start();
    }
  }

  /// Broadcasts the current state to all clients.
  Future<void> _broadcastState() async {
    await AudioServiceBackground.setState(
      controls: [
        MediaControl.skipToPrevious,
        if (_player.playing) MediaControl.pause else MediaControl.play,
        MediaControl.stop,
        MediaControl.skipToNext,
      ],
      systemActions: [
        MediaAction.seekTo,
        MediaAction.seekForward,
        MediaAction.seekBackward,
      ],
      androidCompactActions: [0, 1, 3],
      processingState: _getProcessingState(),
      playing: _player.playing,
      position: _player.position,
      bufferedPosition: _player.bufferedPosition,
      speed: _player.speed,
    );
  }

  AudioProcessingState _getProcessingState() {
    switch (_player.processingState) {
      case ProcessingState.idle:
        return AudioProcessingState.stopped;
      case ProcessingState.loading:
        return AudioProcessingState.connecting;
      case ProcessingState.buffering:
        return AudioProcessingState.buffering;
      case ProcessingState.ready:
        return AudioProcessingState.ready;
      case ProcessingState.completed:
        return AudioProcessingState.completed;
      default:
        throw Exception("Invalid state: ${_player.processingState}");
    }
  }
}

This is the full code for AudioService in-case needed.



Read more here: https://stackoverflow.com/questions/66278441/how-to-send-data-to-audioservicetask-class-which-extends-backgroundaudiotask-fro

Content Attribution

This content was originally published by Ankit Sangwan at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: