Как создать программу для просмотра видео

Всем привет. Хочу попробовать сделать видео плеер, который будет читать следующие форматы: AVI, WMV, MOV, MKV, 3gp и т.д. Подскажите, какие есть библиотеки, которые можно использовать бесплатно и которые позволят читать данные форматы? И если можно то дайте литературу в которой есть описание работы с данными библиотеками) Хочу разобраться как это работает на примере создания собственного видео плеера)

Отслеживать
задан 30 мая 2017 в 5:45
720 15 15 серебряных знаков 35 35 бронзовых знаков
Какой GUI ? UWP WPF WinForms консольный?
30 мая 2017 в 6:20
30 мая 2017 в 6:21
На каких ОС должен запускаться?

Мультиплатформенный?
30 мая 2017 в 6:23
30 мая 2017 в 6:24
тогда вышеперечисленное не подойдёт
30 мая 2017 в 6:25

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

а в качестве библиотеки можете спокойно использовать

using Microsoft.DirectX.AudioVideoPlayback;

Посмотрите на эту реализацию в WinForms(хотя таких кодов множество на просторах инета):

Источник: ru.stackoverflow.com

Установка и работа с медиаплеером VLC Media Player

Создаем собственный видеоплеер для сайта без плагинов и модулей

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

А для этого я расскажу вам, какие элементы языка разметки html и новой спецификации html5 следует использовать, как изменить стилевое оформление видеоплеера и конечно же приведу код программы. Давайте приступим!

Короткий путь к получению видео

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

Читайте также:
Через какую программу записать образ на флешку

К тому же есть и другая возможность простой вставки видео. Думаю, каждый из вас видел такую картину, когда на веб-сервисе запускаются видео с YouTube. Так вот это достаточно простой «финт ушами» для разнообразия своего контента роликом и при этом с минимальным количеством затрачиваемых усилий.

НО! Всегда есть и негативные стороны на коротком и простом пути к внедрению видеофайлов. Используя такие варианты решения, вы ограничиваете свой сайт и себя в выборе дизайна видеоплееров.

Так, видео с YouTube нельзя видоизменить. У вас на странице будет висеть плеер с абсолютно стандартным оформлением, в котором вы сможете менять только размер окна. С плагинами дело обстоит аналогично.

Youtube видеоплеер

Лучшие бесплатные программы для просмотра фотографий

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

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

Реализация персонального видеоплеера

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

Video

How-to: Creating a complete Audio/Video player

As a conclusion to the last chapters on playing audio and video, I decided to create a more complete sample, where we take advantage of the fact that the MediaPlayer/MediaElement classes can handle both audio and video.

I will take the concepts used in the articles about playing audio and video and combine them with several controls which we have already discussed previously in this article, and turn it all into a WPF Media Player. The result will look something like this:

But that’s just when it plays audio/MP3 files. Once a video is loaded, the interface automatically expands to show the video content inside the window:

Let me tell you a bit about how this thing was built. In the end, you can of course see the entire source code, ready for you to play with.

The interface

The interface has been split into three vertical areas: The top, where the toolbar is located, the middle, where the video (if a video file is loaded) is shown, and the bottom, where we find a status bar, complete with a time status, a Slider for seeing and controlling progress and a ProgressBar for showing the volume. All of the controls used here have been explained previously in the tutorial, so we won’t focus too much on that.

Читайте также:
Целевая воспитательная программа это

Notice the use of WPF commands, instead of click events for the buttons. This allows us to easily re-use the functionality in case we want to add e.g. a main menu or a context menu with some of the same functionality. It also makes it easier for us to toggle the functionality on and off, depending on the current state of the player.

Also notice that we have set the MediaElement Stretch property to None, and the Window SizeToContentMode to WidthAndHeight. This is what keeps the window to the minimum size needed to show the interface as well as the video, if one is playing.

For showing the Volume, we’ve used a ProgressBar control in the lower, right corner. This doesn’t currently let the user control the volume, but merely reflects the Volume property on the MediaElement control, through a classic data binding. We’ve implemented a small but neat trick for letting the user control the volume anyway though — more on that below.

The code

In Code-behind, we re-use several techniques already used in our previous examples. For instance, we initiate a DispatcherTimer and let it tick every second, to show the current playback progress in the interface. In the Tick event of the timer, we update Slider control, by settingMinimum, Maximum and current Value according to the file being played, and by hooking up to the ValueChanged event on the slider, we use that to update the label showing the current playback progress in hours, minutes and seconds.

The Slider control also allows the user to skip to another part of the file, simply by dragging the «thumb» to another location. We handle this by implementing events for DragStarted and DragCompleted — the first one to set a variable ( userIsDraggingSlider) that tells the timer not to update the Slider while we drag, and the second one to skip to the designated part when the user releases the mouse button.

Читайте также:
Полномочия какого из пользователей ограничиваются с помощью программы restrick exe

There are CanExecute and Executed handlers for the four commands we use and especially the ones for Pause and Stop are interesting. Since we can’t get a current state from the MediaElement control, we have to keep track of the current state ourselves. This is done with a local variable called mediaPlayerIsPlaying, which we regularly check to see if the Pause and Stop buttons should be enabled.

The last little detail you should notice is the Grid_MouseWheel event. The main Grid covers the entire window, so by subscribing to this event, we get notified when the user scrolls the wheel. When that happens, as a little gimmick, we turn the volume up or down, depending on the direction (we get that by looking at the Delta property, which is negative when scrolling down and positive when scrolling up). This is immediately reflected in the user interface, where a ProgressBar control is bound to the Volume property of the MediaElement.

The complete source code

With all the theory behind the example described, here’s the complete source code:

00:00:00 » />

Summary

The code listing might look a bit overwhelming, but as you can see, there’s a lot of repetition in it. If you take that out of the picture, you will soon realize that creating a pretty capable media player in WPF is really not that hard! Feel free to expand on this example for your own projects — how about implementing a playlist feature?

This article has been fully translated into the following languages:

Is your preferred language not on the list? Click here to help us translate this article into your language!

Источник: wpf-tutorial.com

Рейтинг
( Пока оценок нет )
Загрузка ...
EFT-Soft.ru