Chromecast from android app

Chromecast from android app

Краткое описание:
Официальное приложение от Google для управления Chromecast.

Chromecast позволяет без труда просматривать интернет-видео и любые сайты на экране телевизора. Подключите его к любому HD-телевизору и управляйте через смартфон или планшетный ПК. Никакие пульты при этом не нужны. Транслируйте свои любимые видео из Google Play, YouTube, Netflix и браузера Chrome на телеэкран одним нажатием кнопки.
Подробнее на странице http://www.google.com/chromecast.
При помощи приложения Chromecast вы можете:• Настраивать подключение Chromecast к сети Wi-Fi.• Управлять настройками Chromecast (переименование устройства, изменение пароля сети Wi-Fi и т. д.).

Требуется Android: 6.0+
Русский интерфейс: Нет

Версия: 1.24.37.4 Google Cast (Пост Meoweom #63523221)
Версия: 1.20.9 Google Cast (Пост speed888 #56838550)
Версия: 1.19.26 Google Cast (Пост VLADFIONOV #54411878)
Версия: 1.17.15 Google Cast (Пост VLADFIONOV #52485434)
Версия: 1.15.7 Google Cast (Пост VLADFIONOV #49541392)
Версия: 1.14.11 Chromecast (Пост VLADFIONOV #48256779)
версия: 1.13.15 Chromecast (Пост vutak #46583758)
версия: 1.13.13 Chromecast (Пост Ansaros #40593790)
версия: 1.12.32 Chromecast (Пост Ansaros #40593790)
версия: 1.11.9 Chromecast (Пост pyshnyi #40273200)
версия: 1.10.2 Chromecast (Пост #36573429)
версия: 1.9.6 Chromecast (Пост #36405622)
версия: 1.8.22 Chromecast (Пост #34822950)
версия: 1.7.4 https://4pda.to/forum/d…s.chromecast.app-1.apk
версия: 1.5.5 Chromecast (Пост #32524466)
версия: 1.5.3 Chromecast (Пост #30297486)
версия: 1.3.10 https://4pda.to/forum/dl/post/3745846/Chromecast_1_3_10.apk
версия: 1.1.1com.google.android.apps.chromecast.app.apk ( 2.9 МБ )

Сообщение отредактировал gar_alex — 02.11.21, 08:35

Источник

Смотрю и слушаю где хочу. Интегрируем Chromecast в Android-приложение

На улице я часто слушаю аудиокниги и подкасты со смартфона. Когда прихожу домой, мне хочется продолжить слушать их на Android TV или Google Home. Но далеко не все приложения поддерживают Chromecast. А было бы удобно.

По статистике Google за последние 3 года, количество девайсов на Android TV увеличилось в 4 раза, а число партнеров-производителей уже превысило сотню: «умные» телевизоры, колонки, TV-приставки. Все они поддерживают Chromecast. Но в маркете ещё много приложений, которым явно не хватает интеграции с ним.

В этой статье я хочу поделиться своим опытом интеграции Chromecast в Android-приложение для воспроизведения медиа-контента.

Как это работает

Если вы впервые слышите слово «Chromecast», то постараюсь вкратце рассказать. С точки зрения пользования, это выглядит примерно так:

  1. Пользователь слушает музыку или смотрит видео через приложение или веб-сайт.
  2. В локальной сети появляется Chromecast-девайс.
  3. В интерфейсе плеера должна появиться соответствующая кнопка.
  4. Нажав её, пользователь выбирает нужный девайс из списка. Это может быть Nexus Player, Android TV или «умная» колонка.
  5. Дальше воспроизведение продолжается именно с этого девайса.

Технически происходит примерно следующее:

  1. Google Services отслеживают наличие Chromecast девайсов в локальной сети посредством бродкастинга.
  2. Если к вашему приложению подключен MediaRouter, то вам придёт событие об этом.
  3. Когда пользователь выбирает Cast-девайс, и подключается к нему, открывается новая медиа-сессия (CastSession).
  4. Уже в созданную сессию мы будем передавать контент для воспроизведения.
    Звучит очень просто.

Интеграция

У Google есть свой SDK для работы с Chromecast, но он плохо покрыт документацией, а его код обфусцирован. Поэтому многие вещи пришлось проверять методом тыка. Давайте обо всём по порядку.

Инициализация

Для начала нам надо подключить Cast Application Framework и MediaRouter:

Затем Cast Framework должен получить идентификатор приложения (об этом позже), и типы поддерживаемого медиаконтента. То есть если у нас приложение воспроизводит только видео, то кастинг на колонку Google Home будет невозможен, и в списке девайсов её не будет. Для этого нужно создать реализацию OptionsProvider:

И объявить его в Manifest:

Регистрируем приложение

Чтобы Chromecast мог работать с нашим приложением, его необходимо зарегистрировать в Google Cast SDK Developers Console. Для этого потребуется аккаунт Chromecast разработчика (не путать с аккаунтом разработчика Google Play). При регистрации придётся внести разовый взнос в 5$. После публикации ChromeCast Application нужно немного подождать.
В консоли можно изменить внешний вид Cast-плеера для девайсов с экраном и посмотреть аналитику кастинга в рамках приложения.

MediaRouter

MediaRouteFramework – это механизм, который позволяет находить все удалённые устройства воспроизведения вблизи пользователя. Это может быть не только Chromecast, но и удалённые дисплеи и колонки с использованием сторонних протоколов. Но нас интересует именно Chromecast.

В MediaRouteFramework есть View, которая отражает состояние медиароутера. Есть два способа её подключить:

А из кода требуется всего лишь зарегистрировать кнопку в CastButtonFactory. тогда в нее будет прокидываться текущее состояние медиароутера:

Теперь, когда приложение зарегистрировано, и MediaRouter настроен, можно подключаться к ChromeCast-девайсам и открывать сессии к ним.

Кастинг медиаконтента

ChromeCast поддерживает три основных вида контента:

В зависимости от настроек плеера, типа медиаконтента и cast-девайса, интерфейс плеера может отличаться.

CastSession

Итак, пользователь выбрал нужный девайс, CastFramework открыл новую сессию. Теперь наша задача заключается в том, чтобы отреагировать на это и передать девайсу информацию для воспроизведения.
Чтобы узнать текущее состояние сессии и подписаться на обновление этого состояния, воспользуемся объектом SessionManager:

А ещё можем узнать, нет ли открытой сессии в данный момент:

У нас есть два основных условия, при которых мы можем начинать кастинг:

  1. Сессия уже открыта.
  2. Есть контент для кастинга.
Читайте также:  Музыкальный проигрыватель по умолчанию android

При каждом из этих двух событий можем проверять состояние, и если всё в порядке, то начинать кастить.

Кастинг

Теперь, когда у нас есть что кастить и куда кастить, можем перейти к самому главному. Помимо всего прочего, у CastSession есть объект RemoteMediaClient, который отвечает за состояние воспроизведения медиаконтента. С ним и будем работать.

Создадим MediaMetadata, где будет храниться информация об авторе, альбоме и т. д. Очень похоже на то, что мы передаём в MediaSession, когда начинаем локальное воспроизведение.

Параметров у MediaMetadata много, и их лучше посмотреть в документации. Приятно удивило, что можно добавить изображение не через bitmap, а просто ссылкой внутри WebImage.

Объект MediaInfo несёт информацию о метаданных контента и будет говорить о том, откуда медиаконтент брать, какого он типа, как его проигрывать:

Напомню, что contentType – это тип контента по спецификации MIME.
Также в MediaInfo можно передать рекламные вставки:

  • setAdBreakClips – принимает список рекламных роликов AdBreakClipInfo с указанием ссылок на контент, заголовка, тайминга и временем, через которое реклама становится пропускаемой.
  • setAdBreaks – информация о разметке и тайминге рекламных вставок.

В MediaLoadOptions мы описываем то, как будем обрабатывать медиапоток (скорость, начальная позиция). Также документация говорит, что через setCredentials можно передать заголовок запроса для авторизации, но у меня запросы от Chromecast не включали в себя заявленные поля для авторизации.

После того как всё готово, мы можем отдать все данные в RemoteMediaClient, и Chromecast начнёт воспроизведение. Важно поставить локальное воспроизведение на паузу.

Обработка событий

Видео заиграло, а что дальше? Что если пользователь нажмёт паузу на телевизоре? Чтобы узнавать о событиях, происходящих со стороны Chromecast, у RemoteMediaClient есть обратные вызовы:

Узнать текущий прогресс тоже просто:

Опыт интеграции с существующим плеером

В приложении, над которым я работал, уже был готовый медиаплеер. Стояла задача интегрировать в него поддержку Chromecast. В основе медиаплеера лежал State Machine, и первой мыслью было добавить новое состояние: «CastingState». Но эта идея сразу была отвергнута, потому что каждое состояние плеера отражает состояние воспроизведения, и не важно, что служит реализацией ExoPlayer или ChromeCast.
Тогда пришла идея сделать некую систему делегатов с расстановкой приоритетов и обработкой «жизненного цикла» плеера. Все делегаты могут получать события о состоянии плеера: Play, Pause и т.д. — но только ведущий делегат будет воспроизводить медиаконтент.

У нас есть примерно такой интерфейс плеера:

Внутри у него будет лежать State Machine с таким множеством состояний:

  • Empty — начальное состояние до инициализации.
  • Preparing — плеер инициализирует воспроизведение медиаконтента.
  • Prepared — медиаданные загружены и готовы к воспроизведению.
  • Playing
  • Paused
  • WaitingForNetwork
  • Error

Раньше каждое состояние при инициализации отдавало команду в ExoPlayer. Теперь оно будет отдавать команду в список Playing-делегатов, и «Ведущий» делегат сможет его обработать. Поскольку делегат реализует все функции плеера, то его тоже можно наследовать от интерфейса плеера и при необходимости использовать отдельно. Тогда абстрактный делегат будет выглядеть так:

Для примера я упростил интерфейсы. В реальности событий немного больше.
Делегатов может быть сколько угодно, как и источников воспроизведения. А делегат для Chromecast может выглядеть примерно так:

Прежде чем отдать команду о воспроизведении, нам надо определиться с ведущим делегатом. Для этого они добавляются в порядке приоритета в плеер, и каждый из них может отдавать состояние своей готовности в методе readyForLeading(). Полный код примера можно увидеть на GitHub.

Есть ли жизнь после ChromeCast

После того как я интегрировал поддержку Chromecast в приложение, мне стало приятнее приходить домой и наслаждаться аудиокнигами не только через наушники, но и через Google Home. Что касается архитектуры, то реализация плееров в разных приложениях может различаться, поэтому не везде такой подход будет уместен. Но для нашей архитектуры это подошло. Надеюсь, эта статья была полезной, и в ближайшем будущем появится больше приложений, умеющих интегрироваться с цифровым окружением!

Источник

15 best Chromecast apps for Android

If you have a Chromecast, you’ll want to check out the best Chromecast apps for Android. You should already have the Google Home app installed as it acts like a control center and content discovery platform for your Chromecast. Additionally, Amazon and Google finally made friends and Amazon Prime Video made its way to Chromecast in 2019. Obviously, you should try that if you have Amazon Prime.

Read more:

BubbleUPnP

Price: Free / $4.69

BubbleUPnP is an application that allows you to float your media literally all over your house. It’s compatible with most current game systems, Roku, Chromecast, mobile devices, tablets, and more. That means you’ll be able to cast your photos, TV shows, movies, and music to virtually any WiFi connected device in your home. It also comes with cloud support. That means you can cast things from your Google Drive and other platforms to your Chromecast. It’s one of the must-have Chromecast apps. You can download it for free to check it out before forking out $4.69 for the pro version.

Google Photos

Price: Free (first 15GB) / Varies

Google Photos is probably the best cloud storage for photographs. The service uploads all of your photos as long as your Google Drive space supports it. Of course, the app has Chromecast support as well. You can put your photos up on the screen. Additionally, you can create collections in Google Photos and use them as your background when you’re not casting anything. I have personally done this with a small collection of 4k wallpapers so that my TV always looks crispy and gorgeous. You can always buy more Google Drive space if you need it.

Читайте также:  Лучшая экономия батареи для андроид

Price: Free trial / $7.99-$11.99 per month / $39.99 per month

Hulu is one of the most popular Chromecast apps. It features current and modern TV shows along with a few movies. It’s also a good spot for anime fans. You can put shows on a watchlist and stream it to your TV via Chromecast. They also recently launched a TV service for $39.99 per month. It includes over 50 channels. The UI is a little clunky, but nothing too serious. The live TV subscription also includes regular Hulu content as well and that makes it a decent bargain. You could definitely do worse. The Chromecast support is excellent as well.

iHeartRadio

Price: Free / $9.99 per month

iHeartRadio is a streaming service. It operates a lot like Pandora. There are stations that you can listen to that play certain types of music. There are also real radio stations that you can tap into. Of course, it also has Chromecast support. iHeartRadio is particularly great around the holidays as their holiday stations are second to none in most cases. It’s completely free to use as long as you can tolerate some advertising. It’s one of the better Chromecast apps for streaming random music.

MediaMonkey

Price: Free / $2.49

MediaMonkey is about your best option for casting to Chromecast with your local music. The app supports it and does an excellent job, although it doesn’t keep the icon on the front page like most others. You have to hit the 3-dot menu button to find the cast option. In any case, we quite like MediaMonkey. The music app doesn’t have the latest UI elements, but it’s highly functional. The real deal is the integration with the desktop client that is about as close as Android ever came to an iTunes syncing experience. The desktop app also includes support for streaming to devices on the same network as well, which may work better in some instances. In any case, MediaMonkey is fairly powerful as long as you don’t mind the older UI.

See more:

Movies Anywhere

Price: Free / Movie prices vary

Movies Anywhere is one of the newer Chromecast apps. It’s a movie aggregate service. It integrates with Google Play Movies, Amazon, iTunes, Vudu, and Disney Anywhere. The app has some bugs. However, it works pretty well for the most part. You buy a movie on any of the aforementioned services and they become available on this app. This is one of the few ways to cast Amazon content to a Chromecast. It also opens up the movie streaming industry a bit. You can shop the sales on any of the aforementioned services and watch it here. The app itself is free. Movies on the various services cost money, obviously.

Netflix

Price: Free trial / $7.99-$13.99 per month

Netflix is definitely one of the must-have Chromecast apps. Everyone knows what Netflix is, what it has, and what it costs so there really isn’t much new information here. It has been continuously updated and improved over the years and the developers have done well with keeping with the latest design trends. Streaming is almost flawless as long as your connection holds out. Their selection is among the best and their original programming is considered on par with the best out there. It’s worth a shot since you can usually get a free trial for signing up.

Pandora Music

Price: Free / $4.99-$9.99 per month

Pandora Radio is one of the most popular Chromecast apps out there. People have been using it for years to discover new music, listen to random radio stations based on their tastes, and more. It’s simple, it works well, and it’s compatible with virtually everything. That includes the Chromecast. Pandora, along with iHeartRadio, are excellent apps to just toss on the TV and jam out for a while. You can pay $4.99 per month to get rid of advertisements. Alternatively, you’ll soon be able to get Pandora Premium for $9.99 per month. That will allow for on-demand streaming of any song in their library. It’s a heavy hitter and it’s a must for Chromecast owners.

Price: Free / $0.99 / $3.99 per month

Plex has consistently been one of the best Chromecast apps available. Plex streams video content from your computer to almost anywhere. The app lets you stream it from your computer to your phone and then directly to the Chromecast. It takes a bit of time to set up because you need a home server on your computer, but it works great once you do. You’ll be able to use most of the features with the free version. However, you will need to fork out a small, one-time fee to use the Android app. You can also get Plex Pass for $3.99 per month. That adds more services and features on top of what you can already do. It’s powerful and the best way to get video from your computer to your TV without a bunch of cables.

Читайте также:  Наложение поверх других окон android xiaomi

Podcast Addict

Price: Free / $4.49

Podcast Addict is one of the best podcast apps and it also has Chromecast support. The UI is a little basic, but it otherwise does everything you would expect a podcast player to do. You can search for, follow, and download over one million different podcasts. Additionally, the app works with audiobooks, live streams, YouTube, SoundCloud, and radio. The Chromecast functionality works as expected and we had no problems using it during our testing. The app is free with ads or $4.49 for the full version. Pocket Casts and Doggcatcher are good alternatives with Chromecast support.

Read more app lists here:

Solid Explorer

Price: Free / $1.99

Solid Explorer is one of many file explorers out there. However, this one comes with Chromecast support. It’s also pretty awesome. You’ll get a Material Design interface, dual pane support, and all of the basic features you’d expect from a file manager. It even supports FTP, SFPT, WebDav, and SMB/CIFS protocols along with cloud storage support. You can pick up a 14-day free trial by downloading the app. After that, it’s $1.99 to keep it for good. It’s a great way to stream your locally stored content and cloud storage content. It’s also great for file management. We recommend this as sort of a catch-all for anything on your phone the other apps on the list don’t cover.

Spotify

Price: Free with ads / $9.99 per month

Spotify took its sweet time getting on the train when it came to Chromecast support. However, it finally did and now it’s one of the best Chromecast apps out there. The streaming service itself has over 30 million tracks along with various radio stations, video content, podcasts, and more. It’s currently the reigning king when it comes to popularity in the streaming business. It’s also compatible with most devices. The $9.99 per month plan gets you in the door while the $14.99 per month plan is their family plan (supports up to six people). They also offer discounts for college students. Google Play Music is another excellent music streaming service with Chromecast support. There is a Lite version of this app. However, it’s not as good as the full version.

VRV and Funimation

Price: Free / $9.99 per month

VRV is one of the newer Chromecast apps. It’s a conglomeration of anime and cartoons streaming channels. Some of them include Crunchyroll, HiDive, Rooster Teeth, RiffTrax, and Geek & Sundry. The app was quite buggy at launch, but has gotten more stable over time. The Chromecast support is pretty good and we experienced no problems during testing. This is better than getting an individual subscriptions to any of these services, although you do miss out on some special rewards for things like Rooster Teeth First or Crunchyroll. This is an outstanding video service, especially for anime fans. You can pick up Funimation (also with Chromecast support) and have enough anime to keep you busy for years.

YouTube, YouTube Music, and Google Play Music

Price: Free / $9.99-$12.99 per month

The YouTube family is arguably the best video and music streaming combination on the Internet. They also all make for great Chromecast apps. YouTube has enough content for multiple lifetimes and YouTube Music is a music streaming extension of that. Google Play Music is kind of in the background these days, but its Chromecast support is still there and it still works well. Between these three apps, you should be able to find any song you could possibly want to listen to and find some fun and entertaining video content to go along with it. You can use YouTube for free. The $12.99 per month subscription removes ads, unlocks all of Google Play Music’s features, and gives you better YouTube music support. We just wish YouTube would focus more on its users than its ad partners when it comes to promoting content, but you can’t win them all.

Any live TV apps

Price: Free / Varies

Live TV apps are huge right now. The main competitors include Sling TV, YouTube TV, Hulu, PlayStation Vue, and DirecTV Now. We talked about Hulu earlier because it has a binge watch service like Netflix. However, the other four all have Chromecast support as well. There are a variety of options. Sling TV offers an a la carte style while YouTube TV has a set number of channels for a single price. We have a video comparing all five of them just below if you want to see the differences. Their costs vary and their quality varies. However, they all work with your Chromecast.

Thank you for reading! Try these out too:

If we missed any of the best Chromecast apps for Android, tell us about them in the comments! You can also click here to check out our best Android app and game lists!

Источник

Оцените статью