- Стрим видео с Android устройства по UDP в JAVA приложение
- Инсталляция пакета VLCJ
- Надо разобраться
- Казалось бы победа?
- Streaming Video in Android Apps
- Premium Option
- 1. Create a New App
- Step 1
- Step 2
- 2. Add VideoView
- Step 1
- Step 2
- 3. Stream a Video File
- Step 1
- 4. Add Playback Controls
- Step 1
- 5. Using MediaPlayer
- Step 1
- Step 2
- Step 3
- Step 4
- Conclusion
- How to Stream Video from Android to PC Easily
- Five Ways to Stream Videos from Android to Computer
- Apowersoft Android Recorder
- ApowerMirror
- LetsView
- AllCast
- Mirroring360
- Conclusion
Стрим видео с Android устройства по UDP в JAVA приложение
Итак, выходим на финишную прямую. Стримить видео с андроида на VLC плеер мы уже научились, теперь осталось только интегрировать окошко с видео в JAVA приложение и начать рулить роботелегой.
В этом нам очень сильно поможет проект с открытым исходным кодом VLCJ CAPRICA.
The vlcj project provides a Java framework to allow an instance of a native VLC media player to be embedded in a Java application.
Идея у ребят простая, но гениальная (реально перцовая). Вместо мучений с библиотеками FFmpeg и прочим, надо сразу вызывать специалиста ядро нормального, функционального и профессионального медиаплеера VLC. И вызвать его прямо из JAVA приложения.
Кому интересно, просим под кат.
Поскольку, в этом вояже хватает подводных камней, то начнём, как водится, с очень простого и лишь затем перейдём к тривиальному.
Инсталляция пакета VLCJ
Первым делом проверьте установленную у вас версию медиапроигрывателя VLC. Свежая версия нам не нужна, там выпилено то, что требуется для udp стрима. Об этом уже говорилось в предыдущем посту. Поэтому качаем версию 2.2.6 Umbrella и заодно тщательно проверяем свой JAVA пакет. Они должны совпадать по разрядности. Если плеер использует 64-разрядную архитектуру, то и JDK обязан быть таким же. А то не взлетит.
После этого уже можно скачать сам пакет библиотек VLCJ
Обратите внимание, что нам нужен пакет vlcj-3.12.1 distribution (zip). Именно он работает с плеерами версий VLC 2.2.x. Разархивировать его можно куда угодно, главное, что не в папку самого VLC, ибо там по именам совпадают два файла. И если вы их перезапишите, кончится всё это полным провалом.
Далее, создаем проект в IDE IntelliJ IDEA (если у вас другое IDE, то ничем помочь не могу) и прописываем необходимые зависимости для интеграции библиотек VLCJ.
Делаем именно так для файлов:
Затем создаем единственный класс и пишем в нём следующую малюсенькую программку.
Да, пока мы пытаемся проигрывать просто файл (как видно из кода). С udp лучше не начинать — не заработает. А файл проигрывается вполне, если вы, конечно, не забыли его с соответствующим именем разместить заранее там, где надо. Думаю, что даже для самого начинающего джависта не составит труда разобраться в вышеприведенном коде.
и создание самого инстанса медиаплеера
А потом мы просто его добавляем в нужную графическую панель:
И всё, файл будет проигрываться именно в этом окошке.
А теперь попробуйте заменить
как мы спокойно делали в прошлом посте для стриминга видео через udp соединение.
Здесь такой номер не пройдёт. Окошко, конечно откроется, но покажет фигу, в смысле темный экран. Хотя никаких логов с ошибкой не будет. Просто не будет ничего.
Надо разобраться
Может быть не хватает кодека H264, который мы выбрали в настройках? Стоп, а как тогда только что проигрывался файл ttt.mp4? Он же не может проигрываться при такой настройке, он же — mp4.
Немедленно приходит понимание того, что библиотека VLCJ запускает только само ядро плеера. А какие там были предварительные настройки она не знает и знать не хочет. То есть, нам надо каким-то образом при запуске JAVA приложения, как-то передать VLC плееру, что мы хотим явно использовать кодек H264 или, допустим, хотим повернуть изображение или что-то ещё.
Оказывается, сделать это можно, используя класс MediaPlayerFactory. Только мы его запускали без аргументов, а можно даже с ними. На stackoverflow.com я тут же нашел простой пример, связанный с поворачиванием изображения:
То есть, чего-то там передаем строчным массивом в медиафабрику и оно там сохраняется для используемого медиаресурса.
Я попробовал этот способ для проигрывания файла и как водится, ничего не заработало. Оказывается, забыли две черточки добавить и разнесли по всему интернету. Пришлось догадываться, используя похожий метод transform.
Короче говоря, должно быть:
Теперь наш эталонный файл перекривило как надо!
Дальше будет уже совсем просто:
Для определения кодека, согласно командной строке VLC мы добавляем в строковый массив строку:
Снова пробуем udp канал
И в этот раз всё работает, обозначая победу человеческого разума. Теперь это окошко с видео или несколько таких окошек вы сможете беспрепятственно портировать в графический интерфейс вашего JAVA приложения.
Казалось бы победа?
Не совсем. Легкое недоумение у меня вызвали временные задержки или по научному, лаги. Сначала они более менее приёмлимые, но если у вас хватит терпения просмотреть видео до конца, то вы увидите, что лаг к концу первой минуты трансляции достигает аж пяти секунд. У меня терпения хватило на 10 минут съемки, но, как ни странно, задержка больше не увеличивалась, а так и осталась в тех же пределах.
Конечно, для просмотра видео с камеры такое сгодится, но для управления роботележкой едва ли. Даже луноход реагировал быстрее в два раза!
Подозрения сразу пали на процессы кэширования и они (подозрения )оказались верными.
Самым наглым оказался:
Он как раз и отжирает по умолчанию практически всё, если ему вовремя не дать по рукам.
Может устроить лаг и:
Поэтому во избежание многосекундных задержек рекомендуется добавить во всё тот же строковый массив через запятую следующие строчки:
Параметры там задаются в миллисекундах и поэтому каждый желающий может подобрать их под себя.
Ещё можно использовать ключ:
Тогда медиаплеер будет стараться оптимизировать джитер — подергивание экрана. Но там, чем больше установлено время, тем лучше оптимизируется и это понятно почему. Так что здесь остается лишь искать консенсус и видеть иногда в логах такое безобразие:
Вот хотел он, понимаешь, джиттер исправить, а ты временной промежуток слишком маленький поставил. Теперь сам виноват.
Теперь вроде бы все как надо. Задержку удалось сократить меньше, чем до одной секунды (правда, чуть-чуть меньше).
В итоге, получился совсем крохотный рабочий код
Теперь можно интегрировать видео трансляцию в мою программулину по управлению роботележкой, где раньше я передавал видео по кускам. И надо сказать код весьма упростился, а качество на порядок улучшилось. Плюс ко всему к видео потоку мы можем передать показания
акселерометров
гироскопов
уровня освещения
давления воздуха
показаний компаса
температуры
и даже влажности
При условии, конечно, что все эти сенсоры у вашего смартфона имеются.
И даже включить фару! Автоматически! Если уровень освещения упадёт.
Вряд ли кому особо интересно, но на случай ссылки на гитхаб:
Источник
Streaming Video in Android Apps
The Android platform provides libraries you can use to stream media files, such as remote videos, presenting them for playback in your apps. In this tutorial, we will stream a video file, displaying it using the VideoView component together with a MediaController object to let the user control playback.
We will also briefly run through the process of presenting the video using the MediaPlayer class. If you’ve completed the series on creating a music player for Android, you could use what you learn in this tutorial to further enhance it. You should be able to complete this tutorial if you have developed at least a few Android apps already.
Premium Option
If you want a ready-made solution, check out YoVideo, an Android app template for creating a beautiful mobile video player for Android smartphone.
Users can view videos, follow and share with their friends on Facebook. Using this application template will save you money and time in creating a video-sharing application.
YoVideo on Envato Market
Or you could hire an Android developer to create a custom solution for you. Otherwise, read on for the instructions on how to do it yourself.
1. Create a New App
Step 1
You can use the code in this tutorial to enhance an existing app you are working on or you can create a new app now in Eclipse or Android Studio. Create a new Android project, give it a name of your choice, configure the details, and give it an initial main Activity class and layout.
Step 2
Let’s first configure the project’s manifest for streaming media. Open the manifest file of your project and switch to XML editing in your IDE. For streaming media, you need internet access, so add the following permission inside the manifest element:
2. Add VideoView
Step 1
The Android platform provides the VideoView class in which you can play video files. Let’s add one to the main layout file:
Alter the parent layout to suit your own app if necessary. We give the VideoView instance an id attribute so that we can refer to it later. You may need to adjust the other layout properties for your own design.
Step 2
Now let’s retrieve a reference to the VideoView instance in code. Open your app’s main Activity class and add the following additional imports:
Your Activity class should already contain the onCreate method in which the content view is set:
After the setContentView line, let’s get a reference to the VideoView instance as follows, using the id we set in the XML layout:
3. Stream a Video File
Step 1
Now we can stream a video file to the app. Prepare the URI for the endpoint as follows:
You will of course need to use the remote address for the video file you want to stream. The example here is a public domain video file hosted on the Internet Archive. We parse the address string as a URI so that we can pass it to the VideoView object:
Now you can simply start playback:
The Android operating system supports a range of video and media formats, with each device often supporting additional formats on top of this.
As you can see in the Developer Guide, video file formats supported include 3GP, MP4, WEBM, and MKV, depending on the format used and on which platform level the user has installed.
Audio file formats you can expect built-in support for include MP3, MID, OGG, and WAV. You can stream media on Android over RTSP, HTTP, and HTTPS (from Android 3.1).
4. Add Playback Controls
Step 1
We’ve implemented video playback, but the user will expect and be accustomed to having control over it. Again, the Android platform provides resources for handling this using familiar interaction via the MediaController class.
In your Activity class’s onCreate method, before the line in which you call start on the VideoView , create an instance of the class:
Next, set it to use the VideoView instance as its anchor:
And finally, set it as the media controller for the VideoView object:
When you run the app now, the user should be able to control playback of the streaming video, including fast forward and rewind buttons, a play/pause button, and a seek bar control.
The seek bar control is accompanied by the length of the media file on the right and the current playback position on the left. As well as being able to tap along the seek bar to jump to a position in the file, the streaming status is indicated using the same type of display the user will be accustomed to from sites and apps like YouTube.
As you will see when you run the app, the default behavior is for the controls to disappear after a few moments, reappearing when the user touches the screen. You can configure the behavior of the MediaController object in various ways. See the series on creating a music player app for Android for an example of how to do this. You can also enhance media playback by implementing various listeners to configure your app’s behavior.
5. Using MediaPlayer
Step 1
Before we finish, let’s run through an alternative approach for streaming video using the MediaPlayer class, since we used it in the series on creating a music player. You can stream media, including video, to a MediaPlayer object using a surface view. For example, you could use the following layout:
We will refer to the SurfaceView in the implementation of the Activity class.
Step 2
In your Activity class, add the following interfaces:
Your IDE should prompt you to add these unimplemented methods:
We will add to the surfaceCreated and onPrepared methods.
Step 3
To implement playback, add the following instance variables to the class:
In the Activity ‘s onCreate method, you can then start to instantiate these variables using the SurfaceView object you added to the layout:
Step 4
In the surfaceCreated method, set up your media playback resources:
Finally, in the onPrepared method, start playback:
Your video should now play in the MediaPlayer instance when you run the app.
Conclusion
In this tutorial, we have outlined the basics of streaming video on Android using the VideoView and MediaPlayer classes. You could add lots of enhancements to the code we implemented here, for example, by building video or streaming media support into the music player app we created. You may also wish to check out associated resources for Android such as the YouTube Android Player API.
Источник
How to Stream Video from Android to PC Easily
There could be times when you have a video clip or a movie stored on your Android device that you want to watch on a bigger screen at your own comfort. In this case, streaming your device’s screen onto a larger screen such as a PC is the only way that you can do. But is it really possible to stream video from Android to PC? Actually yes, it might sound a little bit complicated yet there are simple ways that you can utilize such as the ones shown as this post goes on.
Five Ways to Stream Videos from Android to Computer
- Apowersoft Android Recorder
- ApowerMirror
- LetsView
- Allcast
- Mirroring360
Apowersoft Android Recorder
The first Android screen mirroring program on our list is called Apowersoft Android Recorder. It is an efficient screen recorder that has an integrated mirroring function. It is capable of streaming videos that you have in your Android device without encountering any concerns. It uses Chromecast function, so there’s no need for any messy cables for it to work. Just set your phone and computer under the same network, then connect the device through the cast function and you’re ready to stream.
Here are the detailed steps on how to stream video from Android to PC using this tool.
- Get and install this Android recorder from the download link below.
- Once installed, go to options and make some basic configurations like display quality, etc. Also, make sure that your Android device and PC are connected in the same network.
- After that, connect your device into the app by enabling the “Cast” function.
- When your device’s screen was mirrored, you can start playing your video from your Android device and enjoy it.
- To end streaming, click the power button to disconnect the device.
While watching your video on your PC, you can also record the portion that you like through the use of its built-in screen recorder. Aside from these, this tool even has a screen capture function in case you need to take a screenshot of video clips.
ApowerMirror
One of the easiest and fastest tools to mirror your phone to your PC is by using this screen sharing platform called ApowerMirror. The smoothness of the interface and the quality of the video it provides what makes the tool very popular to many. In fact, there is no latency upon mirroring. It is a common perception to mirroring apps. Well, take ApowerMirror different from the others since its, reliability is at its finest. Meanwhile here is the guide for you to get started.
- Download ApowerMiror here by clicking the button below.
Note: Make sure to enable USB debugging on your phone prior to connecting both devices.
LetsView
One of the most practical ways to mirror your Android phone to PC is by using a free app called LetsView. It is a free desktop app that can be downloaded on all types of devices platform. That includes Apple and Android devices, Windows, Mac, and Linux computers and most especially across each device. That only proves that you won’t have to think about compatibility issues. The tool supports three ways of connecting: via pin, QR code, and auto-detection. Meanwhile, learn to use the device by reading the following instructions.
- Download and install the app using the download button below.
- Connect both your Android and PC under the same network.
- On your phone, check the name of the PC detected, and tap it. In any case, the name of the PC is not appearing. You can click on “Redetect” and wait until the name of your PC appears.
- Once you tap the name of your PC, the mirroring will begin.
AllCast
Streaming video from Android to PC can be done easily with this second app from our list named AllCast. This tool provides all-around cast function for it is available on Android and iOS devices. So what this app basically does is casting any activities that you have on your screen directly into your PC. This includes streaming your favorite video or gameplay. However, some users claim that this program often fails to work and there are times wherein gameplays are laggy. These are in contradictory to what the program supposed to perform, but it can be due to some cases as well.
To stream videos from Android to PC using this method, you can first install AllCast in Google Play and also install AllCast Receiver extension in your Chrome. After that, you can easily connect your phone into your computer via cast function. Then, you can watch any short clips or movies as much as you want.
Mirroring360
The last app that you can use to stream video to PC is through Mirroring360. This tool started as mirroring program for iOS devices, Windows and Mac devices, and Chrome books. Now it broadens its scope as it came up with versions that work on Android OS as well. Upon using this app, users can display their screen activities from their Android phones to their PC. Streaming videos, playing games and watching online movies are just some of the activities that you can enjoy while using this tool. But since the Android version is just starting, users might experience crashes, lags and unresponsiveness. This is not certain, but these issues can be experienced at some point.
To mirror screen with this tool, just download and install the receiver app to your PC and then get the sender app from Google Play Store. Be sure both devices are connected in the some internet network. Now wait until the app on your Android phone recognizes the app installed on your PC, and then all you need to do is to connect it.
Conclusion
Those are the simple yet efficient ways to stream videos from Android to PC. Displaying activities from your Android device to PC can be difficult to do if you are living decades ago. But with today’s advanced technology, anyone can stream anything from their mobile devices into bigger devices with the help of programs just like the ones discussed above.
Источник