View videos on android

VideoView

Компонент VideoView предназначен для воспроизведения видеоклипов.

Находится в разделе Images. Желательно использовать реальное устройство при тестировании примеров.

Android поддерживает файлы формата 3gp и mp4. Точную информацию по поддержке форматов воспроизведения мультимедийных файлов смотрите на сайте .

Использовать класс VideoView очень просто. Он содержит поверхность (объект Surface), на которую выводится видео, а также инкапсулирует все операции по управлению проигрывателем. Размещаете на экране компонент и указываете путь к воспроизводимому файлу. Можно воспроизводить файлы с флеш-карточки, из ресурсов или с веб-сервера через интернет.

Данный элемент скрывает от разработчика инициализацию медиапроигрывателя, предоставляя удобный и простой API. Чтобы задать видео для воспроизведения, вызовите метод setVideoPath() или setVideoUri(). В качестве единственного параметра они принимают путь к локальному файлу, путь URI к источнику данных или адрес удалённого видеопотока.

Завершив инициализацию, вы получаете возможность управлять воспроизведением с помощью методов start(), stopPlayback(), pause() и seekTo(). VideoView также включает метод setKeepScreenOn() для предотвращения отключения подсветки экрана во время проигрывания.

Код для воспроизведения:

Метод setVideoPath() указывает на файл, который находится на SD-карточке. Не забудьте установить разрешение

Метод videoView.setMediaController(new MediaController(this)); позволяет вывести кнопки паузы и воспроизведения. Кнопки появляются, если коснуться экрана. Можете не использовать данную возможность или отключать программно, используя значение null.

Метод requestFocus() необходим, чтобы компонент получил фокус и реагировал на касания пальцев.

Метод start() позволяет сразу начать воспроизведение файла. Если вам не нужно, то не добавляйте строку в код.

Если вам нужно воспроизвести файл с сервера, то нужно использовать метод setVideoURI:

Не забываем добавить необходимое разрешение для работы через интернет:

Ещё можно поместить файл в папку ресурсов res/raw. В этом случае также надо использовать URI:

Связка с MediaPlayer

Компонент может использовать методы интерфейса, которые используются классом MediaPlayer.

В комментариях дан альтернативный вариант загрузки файла из интернета. Раньше в Android 2.2 пример работал, сейчас я проверил на новых устройствах — видео не показывалось. Не знаю с чем связано.

Источник

Потоковое видео в Android

В этой заметке я хочу рассказать о некоторых подводных камнях, с которыми можно столкнуться при работе с потоковым видео в Android приложениях. Конкретно, речь пойдёт о конвертации видео и протоколах доставки/воспроизведения видео.
Сразу оговорюсь, что экспертом я в данной области не являюсь, а лишь хочу поделится недавно полученным опытом.

Представим, что перед вами стоит задача реализовать Android приложение, способное проигрывать множество файлов, заливаемых пользователями на ваш сервер. Написать свой youtube, с блекджеком и кодеками. Для этого вам придётся решить как минимум две задачи: конвертации видео к поддерживаемому на Android формате, воспроизведение видео с удалённого источника. Рассмотрим обе эти задачи более подробней.

Конвертация видео

И так, прежде чем воспроизвести какое-то видео нашем Android устройстве, надо это видео перекодировать в поддерживаемый формат. В документации к Android чётко обозначен список этих самых форматов.

Для того, что бы перекодировать файлы, заливаемые пользователями на ваш сервис, или же записать поток с TV-тюнера, вам потребуется помощь специальной утилиты ffmpeg, являющейся де-факто стандартом в отрасли. Подробную инструкцию по её установке можно найти на сайте одноимённого проекта.

Наиболее распространённым сейчас (на мой взгляд) способом хранения видео является контейнер MP4 с использованием кодека H.264 AVC. Их мы, собственно, и рассмотрим.

Первым делом обратите внимание, что Android поддерживает не все возможности кодека H.264, а только определённый набор — профиль, именуемый Baseline Profile(BP). Так, например, в BP не входят такие полезные фичи H.264 как CABAC или B-Frames.

Для нас это значит, что если мы будем использовать эти фичи при кодировании видео, то Android проигрывать это видео будет не обязан. Хотя и может, если ваш телефон достаточно мощный и вендор позаботился об установке и поддержке дополнительных кодеков. Так, например, видео в Main Profile без проблем проигрывается на Samsung Galaxy SII. На телефонах же обычного класса (например, Samsung Galaxy Ace) мы получим сообщение о невозможности воспроизведения видео и ошибку с кодом неверного кодека в logcat‘е.

Но перейдём от теории к практике. Для того, что бы пережать видео, необходимо выполнить следующую команду:

ffmpeg -i in.3gp -f mp4
-vcodec libx264 -vprofile baseline -b:v 1500K
-acodec libfaac -b:a 128k -ar 44100 -ac 2
-y out.mp4

Рассмотрим подробнее каждый из параметров:

  • -i src входной (перекодируемый) файл;
  • -f mp4 используемый видеоконтейнер;
  • -vcodec libx264 используемый видеокодек;
  • -vprofile baseline используемый профиль;
  • -b:v 1500K bitrate;
  • -acodec libfaac используемый аудиокодек;
  • -b:a 128k аудио bitrate;
  • -ar 44100 частота звука;
  • -ac 2 количество аудиопотоков;
  • -y флаг перезаписи выходного файла;

Так же стоит отметить, что можно обойтись и без указания профиля, а явно включить/отключить нужные опции кодека H.264 через параметр -x264opts, так что бы они удовлетворяли условиям BP. Но это же занятие для любителей.

Раздача видео

Самый простой способ воспроизвести видео с удалённого сервера — это скачать его во временное хранилище и воспроизвести локально. Однако, думаю всем понятно, что в виду размеров современных видеозаписей — это не вариант.

Как же быть? Платформа Android предлагает нам нативную поддержку следующих технологий/протоколов:

  • HTTP/HTTPS progressive streaming;
  • HTTP/HTTPS live streaming;
  • RTSP (RTP, SDP);

Рассмотрим их по порядку.

Progressive streaming

Наиболее простой способ раздачи видео с помощью обычного web-сервера, сводящийся по сути к скачиванию заранее подготовленного файла по HTTP(S) протоколу. Вся соль в данном случае заключается в том, что воспроизведение файла начинается не по окончанию загрузки, а как только будет скачано достаточно данных (наполнен некоторый буфер).

Тут стоит уточнить, что при использовании контейнера MP4, необходимо сформировать файл так, что бы метаданные о видео потоке (moov atoms) располагались в начале файла (после атома ftyp), перед видеоданными (mdat atoms). Сделать это можно с помощью обработки файла утилитой qt-faststart:

Читайте также:  Визуальная новелла когда плачут цикады для андроид

Основной проблемой progressive streaming‘а является невозможность перемотки видео к нескачанному моменту, наличие достаточного количества свободного места на устройстве и необходимость поддержки большого числа «толстых» клиентов, скачивающих видео, на web-сервере.

Воспроизведение с помощью данной технологии поддерживается платформой Android нативно. Вы без проблем (если не считать канал связи, мощность девайса и наличие свободного места) сможете проиграть удалённый файл с помощью стандартного класса MediaPlayer.

Pseudo streaming

Данная технология является логическим расширением progressive streaming‘a и позволяет решить одну из его главных проблем — перемотки к ещё не скачанному фрагменту. Применима для контейнеров MP4/FLV с кодеком H.264/AAC.

Единственным отличием от progressive streaming‘a в данным случае является, тот факт, что вам потребуется специальный web-сервер, который с учётом временной метки в GET-запросе будет отдавать нужный вам фрагмент видео файла. Примером такого web-сервера естественно может служить православный NGINX с его ngx_http_mp4_module.

Мне не удалось найти какой-либо официальной информации относительно поддержки данного стандарта в Android. Однако, эмперическим путём было установлено, что она присутствует как минимум на устройствах HTC Desire и Samsung Galaxy SII. Однако, хочу обратить внимание, что да же в случае отсутствия нативной поддержки на вашем устройстве всегда можно воспользоваться сторонними плеерами типа MX Player, которые самостоятельно реализуют логику скачки и воспроизведения фрагментов видео с нужной временной меткой, что позволяет организовать перемотку.

Live streaming

Довольно нестандартный протокол передачи данных от компании Apple. Суть его сводится к тому, что раздаваемый файл «пилится» на множество небольших частей, объединяемых спецтальным файлом-playlist’ом формата M3U8. Передача данных происходит по протоколу HTTP(S).

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

Однако, появляются и проблемы. Для «распила» файла и создания playlist’а потребуется ресурсы процессора, время и место на сервере. Для вещания файла в сеть, как и в предыдущих примерах, потребуется HTTP сервер (без каких-либо дополнительных модулей).

«Распилить» видео файл можно использовать VLC:

Воспроизвести такой файл можно по URL localhost/pornofilm.m3u8.

Поддержка HTTP Live Streaming на нативном уровне в Android присутствует начиная с версии 3.0. С помощью сторонних плееров (DicePlayer, MX Player), судя по wiki, можно добиться поддержки с версии 2.2.

Real Time Streaming Protocol (RTSP)

Протокол прикладного уровня с поддержкой состояния, разработанный специально для передачи видео. Формат команд очень напоминает HTTP. Сами же команды напоминают кнопки на обычном кассетном магнитофоне: PLAY, PAUSE, RECORD и т.д.

В отличие от HTTP Live Streaming RTSP не требует разбиения фалов на мелкие части и составления playlist’ов. Нужные части файла будут генерироваться и отдаваться клиенту налету. В качестве RTSP сервера можно использовать VLC.

Стоит заметить, что сам протокол RTSP не определяет способ передачи данных, а делегирует это другим протоколам. Например, RTP. Для вещания файла по протоколу RTP нужно будет запустить VLC со следующими параметрами:

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

Поэтому вернёмся к протоколу RTSP и воспроизведению видео по требованию (Vidoe On Demand). Для того, что бы использовать VLC в качестве RTSP сервера для проигрывания VOD необходимо прежде всего запустить VLC, указав атрибуты RTSP сервера и Telnet интерфейса:

vlc -vvv -I telnet —telnet-password 123 —rtsp-host 127.0.0.1 —rtsp-port 5554

После этого как сервер запущен, необходимо произвести его настройку. Делать это удобнее всего с помощью telnet‘a, так как такой подход даёт возможность настройки налету:

setup porno input /path/to/pornofilm.mpg

Для воспроизведения видео (в том числе и на платформе Android) необходимо запросить его по URL rtsp://localhost:5554/pornofilm.

Из недостатков можно отметить тот факт, что HTTP открыт зачастую на всех firewall’ах и проксях… с RTSP в случае политики Deny,Allow всё иначе.

Кроме того, при использовании RTSP-сервера для добавления/удаления файлов на сервере придётся обновлять его конфигурацию (список vod’ов). Да, для этого есть telnet, но это всё равно сложнее, чем просто заливать или удалять файлы из каталогов web-сервера.

Воспроизведение с помощью данной технологии поддерживается платформой Android нативно. Например, с помощью всё того же стандартного класса MediaPlayer.

Multicast

Многие считают, что multicast не работает в Android. Это не совсем так.

Во первых, в большинстве случаев он просто отключен по умлочанию, что бы не грузить ресурсы девайса лишней работой. Его можно просто включить.

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

Однако, как показывает практика, проигрывать multicast видео на Android всё можно. В моём случае с этой задачей удачно справился недавно вышедший VLC Beta для Android.

Кроме того с помощью VLC-сервера всегда можно свести воспроизведение multicast‘a к HLS:

new multicast-porno vod enabled

setup multicast-porno input udp://@192.168.20.1:1234

Попытать удачу с проигрыванием multicast’a на вашем устройстве вы можете, передав плееру URL вида udp://@192.168.20.1:1234.

Что выбрать

Если с форматом видео всё ясно (H.264 BP / MP4), то со спобом дистрибуции вопрос открыт. У каждого их них есть свои достоинства и недостатки.

Первым делом из рассмотрения я бы убрал обычный progressive streaming. Да он работает всегда и везде, но отсутствие перемотки и загрузка всего файла целиком — это уже слишком.

Следующим кандидатом на вылет является live streaming. Главным его недостатком является нативная поддержка в Android начиная с версии 3.0. А игнорирование более 80% пользователей c версией 2.x — не вариант. Хотя тут можно посмотреть на сторонний плеер, или заняться собственной реализацией (свободных наработок для поддержки HLS я, увы, не нашёл).

И последним я бы вычеркнул RTSP. Да, это протокол, разработанный специально для видео. Да, его использование идейно верно. Но есть два момента. Во первых — необходимо постоянно обновлять конфигурацию сервера. Во вторых, HTTP открыт всегда и везде, чего нельзя сказать о RTSP/RTP.

Лично я бы остановился на pseudo streaming. Он позволяет осуществлять перемотку и при этом не скачивать весь файл полностью. От нас требуется только немного донастроить web-сервер.

Источник

Android Videoview Tutorial | Play Video From URL Programmatically

Hello Coders, Welcome to Android Videoview tutorial with example in android studio.

One of the primary uses for smartphones and tablets is to enable the user to access and consume content. One key form of content widely used, especially in the case of tablet devices, is video.

Videoview is used to play a video file (.mp4, .avi, .mkv etc formats) in an android application.

Every android app consisting a video player is using a videoview to display a video file.

Two practical example are covered in this tutorial.

Videoview provides some in build features like play, pause, stop, next, previous etc. features.

Читайте также:  Лучший плеер для android 4pda

This is a visual component which, when added to the layout of an activity, provides a surface onto which a video may be played.

The simplest possible way to play a video clip in your app, is to use the videoview class to play the video, and the MediaController class as the UI to control it.

Your app can play media files from a variety of sources, including embedded in the app’s resources, stored on external media such as an SD card, or streamed from the internet.

Android VideoView class has several methods, using which, you can control the media and video player.

Following are the methods of the Android VideoView class.

VideoView Methods

You need to add VideoView via two ways. First one is to add User Interface in .xml file and second one is to defined it’s variable in Java or Kotlin File.

You can add UI in xml file with below code

Now let us see some useful methods of VideoView class.

You can set height and width of the video player with the help of the properties like layout_height and layout_width respectively.

1. public void setMediaController (MediaController controller) :

This method will set media control object for videoview. This will add controls to our video player. Below are the coding lines

If we do not set mediacontroller, then the video will run till the end every time. User can not pause or stop the video because there are no controls are attached with video view.

I will describe setAnchorView() method later in this tutorial itself.

2. setVideoURI(Uri uri) :

When you want to load video from the local resource, you need to give path to that local video file. This method will use this path as an URI.

As you can see, path is stored in string variable first and then it is converted into uri format, This uri format is then set into the setVideoURI method.

3. requestFocus() :

This method will request focus for specific videoview. If you have more than one video on single page then this method will help to start specific video.

4. setVideoPath(String path):

This method is used to set path of video which is stored in internal or external storage of android device.

5. start() :

This method simply orders videoview to start the video.

Below source code shows how to start the video programmatically.

6. stopPlayBack() :

The current running Video will be stopped when this method is called.

Below lines show how to stop the current running video programmatically.

7. seekTo(int milliSec) :

This method moves the media to specified time position by considering the given mode.

When seekTo is finished, the user will be notified via OnSeekComplete supplied by the user. There is at most one active seekTo processed at any time. If there is a to-be-completed seekTo, new seekTo requests will be queued in such a way that only the last request is kept. When current seekTo is completed, the queued request will be processed if that request is different from just-finished seekTo operation.

8. pause() :

This method will tell the videoview to pause the video at the current position and timeline.

Following code shows how to pause the current video playback programmatically.

9. resume():

Resume method will start the paused video when it is called. Video should be start from the time where it was paused earlier.

Following lines shows usage of this method.

10. isPlaying(): If you want to check if the video is playing or not, then this method will help you out.

This method gives boolean (true or false) output. If the video is playing,then it will return true otherwise false.

Example code for this method:

11. canPause(): This method will tell you whether the videoview is able to pause currently running video or not.

It will also return boolean value. If video is able to be paused then it will return true, otherwise false.

Below are the coding details.

12. canSeekForward():

This method will return true value if video view is able to seek forward, false otherwise.

boolean value will be returned by this method.

13. canSeekBackward():

If video view is not able to seek backward then this method will return false.

It will return true if video is able to seek backward.

14. getDuration():

This method is used to get the total duration of video view.

Duration will be returned in integer format.

15. setOnCompletionListener():

What if you want to do some awesome thing when video is completed? This method will give you an opportunity to accomplish your goal.

Define your set of actions in this method as per below

Above video will restart the video when it has finished it’s streaming.

Methods of MediaController

A video player app without any media control is almost useless for the user.

User always want to control the currently playing video as per various requirements.

Video view class does not provide any controls by default but MediaController class is responsible to add media control buttons into the videoview.

To use a MediaController view, you don’t define it in your layout as you would other views. Instead you instantiate it programmatically in your app’s onCreate() method and then attach it to a media player.

Media controls will flop up at the bottom of the screen.

1.setAnchorView():

This method will help mediacontroller to set anchor view for all the controls like pause, stop, forward, backward etc.

Example lines are like below

2. show()

Use this method to show the controller on the screen.

It will go away automatically after 3 seconds of inactivity.

Usage is as follows

3. show(int timeout)

Show the controller on the screen with this method. It will go away automatically after ‘timeout‘ milliseconds of inactivity.

Use 0 to show the controller until the hide() method is called.

If you write above, then controls go away after 5 seconds.

4. hide()

Use this method to remove the controller from the screen.

If you do not want to allow user to interrupt the stream, use this method.

5. isShowing()

This method returns a boolean value about whether the controller is visible to user or not.

If it returns true then controller is visible otherwise not.

6. onTouchEvent()

Implement this method to handle touch screen motion events.

If you have read these method description, then let us make a practical example with android videoview.

Читайте также:  Android tv box с av выходом

1. Android Play Video in VideoView Programmatically

Today you will learn how to play videos in android’s Videoview from a raw folder of android studio directory.

You will also learn how to play video continuously in this tutorial.

First of all checkout output of this videoview android studio example then we will implement it.

Step 2: Updating activity_main.xml file

Add below code in activity_main.xml file

Step 3: Adding resource directory “raw” under “res” directory.

Now we need to create raw directory, in which we will save our video.

Follow below steps

One left left click on res directory at left menu side of android studio.

One Right click on res directory, one menu will open.

From that menu, follow New-> Android resource directory

Create raw directory

When you click on Android resource directory, one dialog will open.

In Directory name give value as “raw.

Now save your video in the raw directory.

Step 4: Updating MainActivity.java class :

Add below code to MainActivity.java

Step 5: Updating AndroidManifest.xml file

add internet permission between …. tag.

Step 6: Description of MainActivity.java

  • Below code
  • will set mediacontrollers(previous, pause, play, next buttons) to videoview.
  • Below code

Here you need to update your package name.

Replace your package name with com.exampledemo.parsaniahardik.videoviewdemonuts

Also replace name of your video with funn in R.raw.funn

Following code will run when video has finished it’s run. vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() < @Override public void onCompletion(MediaPlayer mp) < if(isContinuously)< vv.start(); >> >); As you can see we are using boolean isContinuously todetect which button is pressed, Either “ONCE” or “Continuously “.

We are managing isContinuously and starting video on both button’s click method as below.

2. Android Play video From URL in VideoView

Hello, coders. In this load and play video from URL android studio tutorial example, we will learn to play or load video from URL or server.

You can load video from URL in android Videoview programmatically.

First, check the output of this load and play video from URL Android and then we will implement it step by step.

Step 2: Updating AndroidManifest.xml file

add internet permission between …. tag.

Step 3: Updating activity_main.xml file

Add below code in activity_main.xml file

Step 4: Updating MainActivity.java class :

Add below code to MainActivity.java

Step 5: Description of MainActivity.java

will set mediacontrollers(previous, pause, play, next buttons) to videoview.

Here you need to update your server URL to the video.

The Following code will run when a video has finished it’s run. vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() < @Override public void onCompletion(MediaPlayer mp) < if(isContinuously)< vv.start(); >> >);

As you can see we are using boolean isContinuously todetect which button is pressed, Either “ONCE” or “Continuously .

We are managing isContinuously and starting a video on both button’s click method as below.

We will remove progressBar when a video is prepared to run. See below code

3. Android Kotlin VideoView Tutorial Example

Hello Coders, Welcome to Videoview android kotlin tutorial example. Today you will learn how to play videos in android’s Videoview from a raw folder of android studio directory.

You will also learn how to play video continuously in this tutorial.

Step 2: Updating activity_main.xml file

Add below code in activity_main.xml file

Step 3: Adding resource directory “raw” under “res” directory.

Now we need to create raw directory, in which we will save our video.

Follow below steps

One left left click on res directory at left menu side of android studio.

One Right click on res directory, one menu will open.

From that menu, follow New-> Android resource directory

  • When you click on Android resource directory, one dialog will open.
  • In Directory name give value as “raw.

Now save your video in the raw directory.

Step 4: Updating MainActivity.kt class :

Add below code to MainActivity.kt

Step 5: Updating AndroidManifest.xml file

add internet permission between …. tag.

Step 6: Description of MainActivity.kt

  • Below code
  • will set mediacontrollers(previous, pause, play, next buttons) to videoview.
  • Below code

Here you need to update your package name.

Replace your package name with com.exampledemo.parsaniahardik.videoviewdemonuts

Also replace name of your video with funn in R.raw.funn

Following code will run when video has finished it’s run.

  • As you can see we are using boolean isContinuously todetect which button is pressed, Either “ONCE” or “Continuously “.
  • We are managing isContinuously and starting video on both button’s click method as below.

So that is all for this videoview android studio kotlin example. Thank you for your interest, keep visiting for more cutting edge tutorials. 🙂

4. Android Kotlin Play Video From URL

In this load and play video from URL android kotlin tutorial example, we will learn to play or load video from URL or server.

You can load video from URL in android Videoview programmatically.

A small android app which include play, stop, play continuously and play once options.

You can implement this module any other android app as it includes only one class which is simple and easy.

It will be small video control app with kotlin and android studio.

Step 1: Updating AndroidManifest.xml file

add internet permission between …. tag.

Step 3: Updating activity_main.xml file

Add below code in activity_main.xml file

Step 4: Updating MainActivity.kt class :

Add below code to MainActivity.kt

Step 5: Description of MainActivity.java

  • Below code
  • will set mediacontrollers(previous, pause, play, next buttons) to videoview.
  • Below code

Here you need to update your server URL to the video.

The Following code will run when a video has finished it’s run.

As you can see we are using boolean isContinuously todetect which button is pressed, Either “ONCE” or “Continuously .

We are managing isContinuously and starting a video on both button’s click method as below.

We will remove progressBar when a video is prepared to run. See below code

So that is all for this play video url android kotlin example tutorial. Thank you for your time, keep visiting for more tutorials.

2 thoughts on “Android Videoview Tutorial | Play Video From URL Programmatically”

Can you help me with the app am working on? Trying to put multiple videos in it an ply each one of it when I click it on the list view. I don’t want sequential playing but for the user to play the video he/she chooses to watch. Thanks

are you sure it plays avi format? Cause I can not get avi to play.

Источник

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