tolgatasci
tolgatasci

Reputation: 150

Flutter AudioService get Fetch Url every time

first of all hi,

Start Service

await AudioService.start(
      backgroundTaskEntrypoint: _audioPlayerTaskEntrypoint,
      params: {
        'index': globalIndex,
        'offline': offline,
        'quality': preferredQuality
      },
      androidNotificationChannelName: 'BlackHole',
      androidNotificationColor: 0xFF181818,
      androidNotificationIcon: 'drawable/ic_stat_music_note',
      androidEnableQueue: true,
      androidStopForegroundOnPause: stopServiceOnPause,
    );


      await AudioService.updateQueue(globalQueue);

      await AudioService.play();

Override Here the url part is added. But if I send request to the api for all elements, the performance will be bad.

 @override
  Future<void> onUpdateQueue(List<MediaItem> _queue) async {

    await AudioServiceBackground.setQueue(_queue);

    await AudioServiceBackground.setMediaItem(_queue[index!]);
    concatenatingAudioSource = ConcatenatingAudioSource(
      children: _queue
          .map((item)
      {
        return AudioSource.uri(
         Uri.parse(item.extras!['url'].toString()),
          tag: item);
      }
      )

          .toList(),
    );
    await _player.setAudioSource(concatenatingAudioSource);
    await _player.seek(Duration.zero, index: index);
    queue = _queue;
  }

Instead, how can I make a request to the remote api and update the url without the item playing?

Here is something similar but I couldn't get it to work

How to fetch song details every time from an API before playing in just_audio and audio_service

Upvotes: 0

Views: 211

Answers (1)

tolgatasci
tolgatasci

Reputation: 150

This is how I solved my problem.

 @override
  Future<void> onSkipToQueueItem(String mediaId) async {

    final newIndex = queue.indexWhere((item) => item.id == mediaId);

    if (newIndex == -1) return;

    queue[newIndex].extras!['url'] = await SaavnAPI().get_mp3(queue[newIndex].extras!['url'].toString());


    AudioServiceBackground.setMediaItem(queue[newIndex]);
    _player.setUrl(queue[newIndex].extras!['url'].toString());
    await AudioServiceBackground.setQueue(queue);

    index = newIndex;
    _player.seek(Duration.zero, index: newIndex);
    if (!offline) addRecentlyPlayed(queue[newIndex]);

  }

Upvotes: 0

Related Questions