очередь

Фреймворк Cast предоставляет классы очередей, поддерживающие создание списков экземпляров MediaQueueItem , которые могут быть построены на основе экземпляров MediaInfo таких как видео- или аудиопотоки, для последовательного воспроизведения на приемнике. Эту очередь элементов контента можно редактировать, изменять порядок, обновлять и так далее.

The Receiver SDK maintains the queue and responds to operations on the queue as long as the queue has at least one item currently active (playing or paused). Senders can join the session and add items to the queue. The receiver maintains a session for queue items until the last item completes playback or the sender stops the playback and terminates the session, or until a sender loads a new queue on the receiver. The receiver does not maintain any information about terminated queues by default. Once the last item in the queue finishes, the media session ends and the queue vanishes.

Создание и загрузка элементов очереди мультимедиа

A media queue item is represented in the Cast framework as a MediaQueueItem instance. When you create a media queue item, if you are using the Media Player Library with adaptive content, you can set the preload time so that the player can begin buffering the media queue item before the item ahead of it in the queue finishes playing. Setting the item's autoplay attribute to true allows the receiver to play it automatically. For example, you can use a builder pattern to create your media queue item as follows:

Котлин
val queueItem: MediaQueueItem = MediaQueueItem.Builder(mediaInfo)
    .setAutoplay(true)
    .setPreloadTime(20.0)
    .build()
Java
MediaQueueItem queueItem = new MediaQueueItem.Builder(mediaInfo)
  .setAutoplay(true)
  .setPreloadTime(20)
  .build();

Загрузите массив элементов очереди мультимедиа в очередь, используя соответствующий метод queueLoad объекта RemoteMediaClient .

Получайте обновления статуса очереди воспроизведения.

Когда приемник загружает элемент из очереди воспроизведения, он присваивает этому элементу уникальный идентификатор, который сохраняется на протяжении всей сессии (и на протяжении всего времени существования очереди). Ваше приложение может узнать статус очереди, какой элемент в данный момент загружен (он может не воспроизводиться), загружается или предварительно загружен. Класс MediaStatus предоставляет эту информацию о статусе:

  • Метод getPreloadedItemId() возвращает идентификатор предварительно загруженного элемента, если следующий элемент уже был предварительно загружен.
  • Метод getLoadingItemId() возвращает идентификатор элемента, который в данный момент загружается (но не активен в очереди) на приемнике.
  • Метод getCurrentItemId() возвращает идентификатор элемента, который был активен в очереди (возможно, он не воспроизводился) в момент изменения статуса медиафайла.
  • Метод ` getQueueItems() ` ( устарел, используйте MediaQueue ) возвращает список экземпляров MediaQueueItem в виде неизменяемого списка.

Your app can also get the list of items using the MediaQueue class. The class is a sparse data model of the media queue. It keeps the list of item IDs in the queue, which is automatically synchronized with the receiver. MediaQueue doesn't keep all the MediaQueueItem because it will take too much memory when the queue is very long. Instead, it fetches the items on demand and keeps an LruCache of recently accessed items. You can use these methods to access the media queue:

  • Метод getItemIds() возвращает список всех идентификаторов товаров в порядке их упорядочивания.
  • Метод getItemAtIndex() возвращает кэшированный элемент по заданному индексу. Если элемент не кэширован, MediaQueue вернет null и запланирует его получение. После получения элемента будет вызван метод MediaQueue.Callback#itemsUpdatedAtIndexes() , и повторный вызов getItemAtIndex() с тем же ID вернет элемент.
  • fetchMoteItemsRelativeToIndex() используется, когда пользователь прокручивает интерфейс очереди вверх или вниз, и ваше приложение хочет получить больше элементов из облака.

Используйте эти методы вместе с другими методами отслеживания состояния медиафайлов, чтобы информировать ваше приложение о состоянии очереди и элементах в ней. В дополнение к обновлениям состояния медиафайлов от приемника, ваше приложение может отслеживать изменения в очереди, реализовав RemoteMediaClient.Callback и MediaQueue.Callback .

Кроме того, SDK Cast предоставляет два вспомогательных класса для создания пользовательского интерфейса для организации очередей.

Например, чтобы создать RecyclerView с помощью MediaQueueRecyclerViewAdapter :

Котлин
class MyRecyclerViewAdapter(mediaQueue: MediaQueue?) :
    MediaQueueRecyclerViewAdapter<MyViewHolder?>(mediaQueue) {
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val item = getItem(position)

        // Update the view using `item`.
        ...
    }
}

class MyViewHolder : RecyclerView.ViewHolder {
    // Implement your own ViewHolder.
    ...
}

fun someMethod() {
    val adapter = MyRecyclerViewAdapter(
        mCastSession.remoteMediaClient.getMediaQueue())
    val recyclerView =
        activity.findViewById(R.id.my_recycler_view_id) as RecyclerView
    recyclerView.adapter = adapter
}
Java
public class MyRecyclerViewAdapter extends MediaQueueRecyclerViewAdapter<MyViewHolder> {
    public MyRecyclerViewAdapter(MediaQueue mediaQueue) {
        super(mediaQueue);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
      MediaQueueItem item = getItem(position);

      // Update the view using `item`.
      ...
    }
}

public class MyViewHolder implements RecyclerView.ViewHolder {
  // Implement your own ViewHolder.
  ...
}

public void someMethod() {
    RecyclerView.Adapter adapter = new MyRecyclerViewAdapter(
        mCastSession.getRemoteMediaClient().getMediaQueue());
    RecyclerView recyclerView =
        (RecyclerView) getActivity().findViewById(R.id.my_recycler_view_id);
    recyclerView.setAdapter(adapter);
}

Редактировать очередь

To operate on the items in the queue, use the queue methods of the RemoteMediaClient class. These let you load an array of items into a new queue, insert items into an existing queue, update the properties of items in the queue, make an item jump forward or backward in the queue, set the properties of the queue itself (for example, change the repeatMode algorithm that selects the next item), remove items from the queue, and reorder the items in the queue.