- Hello world!
- Adding ExoPlayer as a dependency
- Add ExoPlayer modules
- Turn on Java 8 support
- Enable multidex
- Creating the player
- A note on threading
- Attaching the player to a view
- Populating the playlist and preparing the player
- Controlling the player
- Онлайн радио для Android: пошаговое руководство
- Авторизуйтесь
- Онлайн радио для Android: пошаговое руководство
- ExoPlayer in Android with Example
- Advantages of Using ExoPlayer
- ExoPlayer vs MediaPlayer
- Step by Step Implementation of ExoPlayer in Android
Hello world!
Another way to get started is to work through the ExoPlayer codelab.
For simple use cases, getting started with ExoPlayer consists of implementing the following steps:
- Add ExoPlayer as a dependency to your project.
- Create an ExoPlayer instance.
- Attach the player to a view (for video output and user input).
- Prepare the player with a MediaItem to play.
- Release the player when done.
These steps are described in more detail below. For a complete example, refer to PlayerActivity in the main demo app.
Adding ExoPlayer as a dependency
Add ExoPlayer modules
The easiest way to get started using ExoPlayer is to add it as a gradle dependency in the build.gradle file of your app module. The following will add a dependency to the full library:
where 2.X.X is your preferred version (the latest version can be found by consulting the release notes).
As an alternative to the full library, you can depend on only the library modules that you actually need. For example the following will add dependencies on the Core, DASH and UI library modules, as might be required for an app that only plays DASH content:
When depending on individual modules they must all be the same version.
The available library modules are listed below. Adding a dependency to the full ExoPlayer library is equivalent to adding dependencies on all of the library modules individually.
- exoplayer-core : Core functionality (required).
- exoplayer-dash : Support for DASH content.
- exoplayer-hls : Support for HLS content.
- exoplayer-rtsp : Support for RTSP content.
- exoplayer-smoothstreaming : Support for SmoothStreaming content.
- exoplayer-transformer : Media transformation functionality.
- exoplayer-ui : UI components and resources for use with ExoPlayer.
In addition to library modules, ExoPlayer has extension modules that depend on external libraries to provide additional functionality. Some extensions are available from the Maven repository, whereas others must be built manually. Browse the extensions directory and their individual READMEs for details.
More information on the library and extension modules that are available can be found on the Google Maven ExoPlayer page.
Turn on Java 8 support
If not enabled already, you need to turn on Java 8 support in all build.gradle files depending on ExoPlayer, by adding the following to the android section:
Enable multidex
If your Gradle minSdkVersion is 20 or lower, you should enable multidex in order to prevent build errors.
Creating the player
You can create an ExoPlayer instance using ExoPlayer.Builder , which provides a range of customization options. The code below is the simplest example of creating an instance.
A note on threading
ExoPlayer instances must be accessed from a single application thread. For the vast majority of cases this should be the application’s main thread. Using the application’s main thread is a requirement when using ExoPlayer’s UI components or the IMA extension.
The thread on which an ExoPlayer instance must be accessed can be explicitly specified by passing a Looper when creating the player. If no Looper is specified, then the Looper of the thread that the player is created on is used, or if that thread does not have a Looper , the Looper of the application’s main thread is used. In all cases the Looper of the thread from which the player must be accessed can be queried using Player.getApplicationLooper .
If you see IllegalStateException being thrown with the message “Player is accessed on the wrong thread”, then some code in your app is accessing an ExoPlayer instance on the wrong thread (the exception’s stack trace shows you where). You can temporarily opt out from these exceptions being thrown by calling ExoPlayer.setThrowsWhenUsingWrongThread(false) , in which case the issue will be logged as a warning instead. Using this opt out is not safe and may result in unexpected or obscure errors. It will be removed in ExoPlayer 2.16.
For more information about ExoPlayer’s threading model, see the “Threading model” section of the ExoPlayer Javadoc.
Attaching the player to a view
The ExoPlayer library provides a range of pre-built UI components for media playback. These include StyledPlayerView , which encapsulates a StyledPlayerControlView , a SubtitleView , and a Surface onto which video is rendered. A StyledPlayerView can be included in your application’s layout xml. Binding the player to the view is as simple as:
You can also use StyledPlayerControlView as a standalone component, which is useful for audio only use cases.
Use of ExoPlayer’s pre-built UI components is optional. For video applications that implement their own UI, the target SurfaceView , TextureView , SurfaceHolder or Surface can be set using ExoPlayer ’s setVideoSurfaceView , setVideoTextureView , setVideoSurfaceHolder and setVideoSurface methods respectively. ExoPlayer ’s addTextOutput method can be used to receive captions that should be rendered during playback.
Populating the playlist and preparing the player
In ExoPlayer every piece of media is represented by a MediaItem . To play a piece of media you need to build a corresponding MediaItem , add it to the player, prepare the player, and call play to start the playback:
ExoPlayer supports playlists directly, so it’s possible to prepare the player with multiple media items to be played one after the other:
The playlist can be updated during playback without the need to prepare the player again. Read more about populating and manipulating the playlist on the Playlists page. Read more about the different options available when building media items, such as clipping and attaching subtitle files, on the Media items page.
Prior to ExoPlayer 2.12, the player needed to be given a MediaSource rather than media items. From 2.12 onwards, the player converts media items to the MediaSource instances that it needs internally. Read more about this process and how it can be customized on the Media sources page. It’s still possible to provide MediaSource instances directly to the player using ExoPlayer.setMediaSource(s) and ExoPlayer.addMediaSource(s) .
Controlling the player
Once the player has been prepared, playback can be controlled by calling methods on the player. Some of the most commonly used methods are listed below.
- play and pause start and pause playback.
- seekTo allows seeking within the media.
- hasPrevious , hasNext , previous and next allow navigating through the playlist.
- setRepeatMode controls if and how media is looped.
- setShuffleModeEnabled controls playlist shuffling.
- setPlaybackParameters adjusts playback speed and audio pitch.
If the player is bound to a StyledPlayerView or StyledPlayerControlView , then user interaction with these components will cause corresponding methods on the player to be invoked.
Источник
Онлайн радио для Android: пошаговое руководство
Авторизуйтесь
Онлайн радио для Android: пошаговое руководство
Рассказывает Николай Коломийцев, технический директор и Android-разработчик LevelTop.org
Привет, типичные! В этом руководстве расскажу вам о том, как создать свое приложение в Android.
Начну сразу с сути, поэтому определимся с функционалом:
- Проигрывание потокового аудио с помощью ExoPlayer.
- Парсинг HTML страницы.
- Интеграция API Last.fm.
- Подключение сервиса для управления проигрыванием из «шторки».
- Работа с кастомными библиотеками.
С требованиями разобрались, теперь самое сложное интересное — реализация.
Весь код вы можете найти на GitHub, здесь же я уделю внимание только основным моментам.
Sportmaster Lab , Санкт-Петербург, Москва, Новосибирск, можно удалённо , От 100 000 до 400 000 ₽
Думаю, что SDK у вас установлено и новые проекты вы создавать умеете, поэтому создадим пустой (blank) проект и добавим библиотеки в build.gradle:
Теперь коротко пройдемся по классам:
- Player — класс для инициализации и управления нашим ExoPlayer.
- NotificationService — класс для проигрывания аудио в фоне и отображения уведомления в шторке.
- Const — класс для описания ссылок на аудио и прочего.
- CircularSeekBar — класс, который я позаимствовал на GitHub, добавляет нам изогнутый SeekBar.
- GetTrackInfo — здесь мы обращаемся к Last.fm, а также парсим HTML страницу.
- MainActivity — главный класс приложения, выполняющий функции отрисовки экрана и инициализации методов.
Также добавим пару layout-файлов для шторки и главного экрана, drawables можно найти здесь:
И добавим нашему Manifest несколько разрешений и служб:
Теперь давайте получим ключ Last.fm API, он нужен нам для того, чтобы по имени исполнителя найти его фотографию и показать ее на главном экране. Для этого нужно перейти на страницу создания аккаунта и войти или зарегистрироваться, после чего вам потребуется создать приложение. Эта операция займет 30 секунд, и мы наконец доберемся до API KEY, его вам нужно ввести в поле LAST_FM_KEY класса Const.java:
Далее предлагаю перейти к способу получения ссылки на прямую трансляцию, ее я беру отсюда. Для этого нам нужно запустить радио и, нажав правой кнопкой мыши в Chrome, выбрать пункт «посмотреть код», после чего выбрать вкладку Network и найти ссылку с самым длинным timeline. Это и будет наш стрим, он уже добавлен в класс Const — аналогичным способом я получил ссылку на HTML-страницу с именем исполнителя и названием трека. В этом коде много костылей, так как парсить HTML — это само по себе странное занятие, но все же я постараюсь его объяснить:
Здесь вы можете видеть получаемый мною нужный фрагмент HTML-страницы:
А это его парсинг, надеюсь, что комментарии будут информативны:
Этот пример кода, вполне возможно, не является лучшей практикой, но все приложение было написано ночью за несколько часов. Парсинг HTML — занятие сложное, и если есть возможность его не использовать, то нужно этой возможностью пользоваться. Надеюсь, мой опыт обработки HTML-страницы кому-то окажется полезным.
Далее парсинг JSON и получение фото пользователя.
Вот пример отправляемого Last.fm JSON-ответа для певицы Adele:
Все, что нас с вами здесь интересует — это изображение размера «mega», парсить мы его будем таким образом:
Теперь немного об ExoPlayer, и почему я не использовал стандартный MediaPlayer. MediaPlayer абсолютно не оптимизирован для таких нагрузок и частенько останавливал трансляцию. Также на старых (старше пятой) версиях Android перемотка, которую я собирался добавить позже, работает так, как будто плеер подгружает всю аудио дорожку между текущим положением и выбранным пользователем. После недолгих поисков выбор пал на ExoPlayer, сейчас коротко опишу его возможности, код ниже можно использовать как отдельный элемент в своем проекте:
Финальный этап урока — это уведомление в шторке, сервис и то, каким образом это работает.
Из главного Activity при начале проигрывания аудио мы запускаем сервис, и он берет всю работу на себя, освобождая работу в Activity. Выглядит это так:
Сервис управляется с помощью Intent. Когда пользователь нажимает на кнопку «play / pause» в шторке, сервис отправляет Intent сам себе и обрабатывает его, так мы отправляем Intent при нажатии:
Поздравляю! Мы разработали клиент-серверное приложение с использованием дополнительных библиотек, воспроизведением аудио, а также работой с сервисами. В конечном итоге получится нечто подобное тому, что вы видите на скриншотах:
Источник
ExoPlayer in Android with Example
ExoPlayerView is one of the most used UI components in many apps such as YouTube, Netflix, and many video streaming platforms. ExoPlayerView is used for audio as well as video streaming in Android apps. Many Google apps use ExoPlayerView for streaming audios and videos. ExoPlayer is a media player library that provides a way to play audio and video with lots of customization in it. It is an alternative that is used to play videos and audios in Android along with MediaPlayer. ExoPlayer is a library that is the best alternative source for playing audio and videos on Android. This library will also help you to customize your media player according to our requirements.
Advantages of Using ExoPlayer
- ExoPlayer provides the support for the playlist and with this, you can clip or merge your media.
- With the help of ExoPlayer, you can directly fetch media files such as audios and videos directly from the internet and play them inside the ExoPlayer.
- It provides smooth encryption and streaming of video and audio files.
- ExoPlayer provides you the ability to customize your media player according to your requirements.
ExoPlayer vs MediaPlayer
MediaPlayer
Step by Step Implementation of ExoPlayer in Android
We will be creating a simple video player app in which we will be fetching a video from a URL and play that video inside our ExoPlayer. Note that we are using JAVA for implementing ExoPlayer in Android.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency to the build.gradle(Module:app)
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
// for core support in exoplayer.
// for adding dash support in our exoplayer.
// for adding hls support in exoplayer.
// for smooth streaming of video in our exoplayer.
// for generating default ui of exoplayer
After adding this dependency sync the project.
Step 3: Add internet permission in your Manifest file
Navigate to the app > manifest folder and write down the following permissions to it.
Источник