Html5 веб камера
Доступ к веб-камере через getUserMedia()
getUserMedia
Исторически единственным способом взаимодействия с локальными ресурсами в Интернете является загрузки файлов. Единственные локальные устройства с которыми вы можете действительно взаимодействовать — это мышь и клавиатура. К счастью, это больше не так. В предыдущей главе мы видели как управлять аудио. В этой главе мы поговорим о веб-камере пользователя.
Прежде всего хочу подчеркнуть, что всё это ещё альфа-версия. API для разговора через локальные устройства неоднократно менялись и, вероятно, будут меняться не раз, прежде чем они станут стандартом. Кроме того только десктопная версия Chrome и Opera имеет реальную поддержку для разговора через веб-камеру. Практически нет поддержки на смартфонах. Используйте эту главу как способ увидеть что наступит в будущем и получите удовольствие играясь с кодом, но ни в коем случае не используйте в рабочем коде. Как упоминалось, давайте повеселимся!
У доступа к локальным устройствам с веб-страницы длинное и пёстрое прошлое. Традиционно это было прерогативой только плагинов, таких как Flash и Java. Ситуация во многом изменилась несколько лет назад. Группа WebRTC нацелилась разрешить коммуникацию в реальном времени в Интернете. Подумайте о видео-чатах и прямой трансляции концертов. Одним из необходимых компонентов для этого выступает доступ к веб-камере. Сегодня мы можем сделать это используя navigator.getUserMedia().
Я собираюсь показать вам метод, который работает в последней версии Chrome. Более надёжное решение показано в этой статье на HTML5 Rocks. Также обратите внимание, что getUserMedia не будет работать с локальными файлами. Вы должны запускать всё на локальном веб-сервере.
Для начала нам потребуется элемент на странице. Там будет выводиться веб-камера.
Чтобы получить доступ к веб-камере, мы должны вначале посмотреть, есть ли поддержка через navigator.webkitGetUserMedia != null . Если существует, тогда мы можем запросить доступ. options определяет что нам требуется: аудио, видео или и то и другое. На момент написания статьи только аудио не работает в Chrome.
При вызове webkitGetUserMedia открывается диалоговое окно, в котором пользователя спрашивают, если наша страница может получить доступ. Если пользователь одобряет, тогда вызывается первая функция. Если возникли какие-либо проблемы, то будет вызвана функция ошибки.
Теперь у нас есть поток, который мы можем присоединить к элементу на странице, с помощью магического URL через webkitURL.createObjectURL() . После подключения элемент покажет живой вид с веб-камеры.
Вот как это выглядит:
Создание снимка
Теперь у нас есть живой поток веб-камеры, но что мы можем с этим сделать? Когда это происходит, элемент красиво воспроизводит на холсте. Мы можем сделать снимок с веб-камеры просто нарисовав на холсте элемент.
При нажатии на кнопку её обработчик событий захватит элемент со страницы и нарисует его на холсте. Мы используем тот же вызов drawImage() , что и для статичных изображений. Через эту же функцию мы можем манипулировать картинкой аналогично работе с изображениями. Для растяжения измените вызов drawImage на показанный ниже:
Вот и всё. Веб-камера это просто изображение. Мы можем модифицировать его, используя некоторые эффекты, описанные в главе про буфер пикселей. Код ниже инвертирует снимок.
Вы можете делать это в живую неоднократно захватывая видео, а не только когда пользователь нажал на кнопку.
Больше крутых хаков
То, что я показал вам, это только верхушка айсберга возможностей. Вот ещё несколько примеров, созданных другими талантливыми разработчиками.
webcamtoy.com в реальном времени делает разные эффекты с веб-камерой, похожих на фильтры Инстаграмма.
Soundstep.com создал ксилофон, которым вы управляете, просто перемещая руки перед веб-камерой. Обратите внимание на датчик движения зрителя в правом нижнем углу.
Микрофон в реальности пока ещё не работает. Вы не можете пока подключить его к аудио-материалам из-за багов, но надеюсь это изменится в ближайшее время.
Webcam V >- HTML5
- JavaScript
Aug 27, 2012
Webcam Video Capture in HTML5 and CSS3 filters
As we know – HTML5 defines a new element called for embedding video. Usually people use this element to embed a video into web page. It is very convenient. Because the element is designed to be usable without any detection scripts. You can just specify multiple video files, and browsers that support HTML5 video will choose one based on what video formats they support. Now, let’s imagine that we can use the same element to access a user’s camera and microphone. Our article opens these boundaries. I’m going to show you how to capture a video from your webcam in HTML5, and even more, I will show you how to pass this video into object, and even – how to apply custom CSS3 filters to our video.
Today we will create a script which will capture a video stream from our webcam (into element), at the right of our element I will put a element, and we will transfer the video from the video object directly into the canvas object. I’m going to use a new HTML5 – navigator.getUserMedia(). This function gives access to a user’s camera and microphone. Also, before we start I would like to inform you that our result works well only in few browsers, this are Chrome (I recommend to use the latest version) and Opera (version 12 and higher). But, it is going to work in future versions of FireFox browser too.
Live Demo
Step 1. HTML
Our basic HTML markup does not contain a big deal, on the contrary – it is very easy:
index.html
There are a warning message (for browsers that do not support this functionality), a element and element.
Step 2. CSS
As I told in the beginning of our tutorial – we are going to use CSS3 filters. It is the time to define all these CSS3 filters:
style.css
As you can see – vendors prefixes are required. It gives possibility to use these filters in all major browsers.
Step 3. HTML5 JavaScript
Now, the most important step – html5, please create an empty script.js file and paste the next code:
script.js
Let’s review our code. In order to use webcam (or microphone) we use new navigator.getUserMedia function. As params, we use
Live Demo
download package
Conclusion
The future is getting closer. I hope that everything is clean for today. If you have any suggestions about further ideas for articles – you are welcome to share them with us. Good luck in your work!
Accessing Your Webcam in HTML
Accessing your webcam via your browser used to involve a. pardon the profanity, a plugin. That’s right. In order to connect to a webcam and gain access to its video stream, you had to rely on something primarily created in Flash or Silverlight. While that approach certainly worked for browsers that supported plug-ins, it didn’t help for the increasing number of browsers that aim to be plugin-free. This inability to natively access the webcam without relying on 3rd party components was certainly a gap in the HTML development story. At least, that was the case until pretty recently.
The W3C has been attempting to fill this gap by encouraging browser vendors to implement the proposals outlined in the Media Capture and Streams spec. This spec defines, among various other things, how to communicate with a webcam device using just a little bit of JavaScript. The good news is, despite its newness, various browsers have already implemented support for accessing the webcam in their latest versions.
Note: Browser Support
Because accessing the webcam natively is a recent introduction, check out caniuse’s statistics to see the level of support it has among the major browsers.) In writing this tutorial, I used the latest version of Google’s Chrome where everything works swimmingly.
So. while the rest of the world is getting upgraded to browsers that support native webcam access, now is a great time for you to get ahead of the program and learn all about it. That’s where this tutorial comes in. By the time you reach the bottom of this page, you will have learned how to take your webcam’s video stream and display it using only some HTML and JavaScript.
The Example
Before proceeding further, let’s first take a look at an example that is >getUserMedia function, you have granted permission for your browser to access the webcam, and you are not on a mobile device like an iPad, iPhone, Android-based phone, etc. you should see a live version of yourself (or whatever your webcam is pointing at) in the gray box below:
Your browser does not support inline frames or is currently configured not to display inline frames.
If you do not give your browser permission to access the webcam, you will not see anything interesting. You will just see a beautiful gray box with a finely crafted dark gray border.
Google Chrome and HTTPS
If you are on a recent version of Google Chrome, a security change was made recently where a webcam can only be accessed if the content is served via HTTPS. You can still develop and test locally (or via localhost), but you won’t be able to test it «in the wild» unless you are on a secure HTTPS connection.
If you didn’t see a permissions notification, you may have just overlooked it or dismissed it because it appeared when you loaded the page. Different browsers do different things when they ask you for permission to use the webcam. For example, here is what Chrome’s prompt looks like:
If you denied permission accidentally (or intentionally), just reload this page to get a crack at acing this test again.
Overview of How This Works
To help make the code we will be writing. easier to write, let’s look at an overview of how everything works using plain old English. There are two components that do all the heavy lifting in getting data from your webcam displayed on your screen. They are the HTML video element and the JavaScript getUserMedia function:
The video element is pretty straightforward in what it does. It is responsible for taking the video stream from your webcam and actually displaying it on the screen.
The interesting piece is the getUserMedia function. This function allows you to do three things:
- Specify whether you want to get video data from the webcam, audio data from a microphone, or both.
- If the user grants permission to access the webcam, specify a success function to call where you can process the webcam data further.
- If the user does not grant permission to access the webcam or your webcam runs into some other kind of error, specify a error function to handle the error conditions.
For what we are trying to do, we call the getUserMedia function and tell it to only retrieve the video from the webcam. I will cover the microphone in the future! Once we retrieve the video, we tell our success function to send the video data to our video element for display on our screen.
If this sounds pretty straightforward, that’s because it actually is pretty. Let’s put all of this straightforward English-sounding description into HTML and JavaScript in the next section.
Adding the Code
In this section, let’s go ahead and display our webcam data to the screen. First, let’s add the HTML and CSS:
In a new document, go ahead and add all of the HTML and CSS that you see above. The important thing to note in this snippet is the video tag:
Our video tag has an id value of v >autoplay attribute is set to true. By setting the autoplay attribute to true, we ensure that our video starts to display automatically once we have our webcam video stream.
If you preview what your page looks like in your browser, what you will see will look as follows:
Yes, this looks pretty plain and boring now. That is because we haven’t added the JavaScript that ties together our video element with your webcam. We’ll do that next!
Ins >script tag, add the following code:
Once you’ve added this code, save your HTML document and preview your page. Provided you are on a supported browser, you should see your webcam video stream after you’ve given your browser permission to access it.
Examining the Code
Now that you have a working example, let’s go through our code line-by-line to understand how the verbal overview you saw earlier matches the code that you just added.
Let’s start at the very top:
We first declare a variable called video , and it is initialized to our video element that lives in the HTML. We get our paws on the video element by using querySelector and specifying the id selector that targets it.
Next up is our code for accessing the getUserMedia API:
The getUserMedia method is supported by most browsers, but it doesn’t hurt to check first before starting to access properties on it. This if statement ensures that our media-related code only works if getUserMedia is actually supported.
The rest of our code is responsible for accessing our webcam and streaming the visuals to the screen. Before we go through and look at that, let’s take a step back and talk about how getUserMedia actually works. It takes one argument that specifies what are known as constraints. Constraints allow you to control, among various things, whether video is allowed, whether audio is allowed, how big to make the video dimensions, whether to prefer a front-facing camera over a back-facing one, the video frame rate, and more. You represent these constraints as just objects and properties. Nothing fancy there.
In our code, you can see constraints in action below:
All we are telling getUserMedia is to specify a constraints object whose video property is set to true. This means that default settings will be used in capturing the visuals and displaying them. This isn’t the most exciting constraint to set, but it gets the job done. To see the full range of constraints you can specify, the MDN article on getUserMedia goes through all the fun details.
Beyond constraints, there is another very important detail we need to know about the getUserMedia method. What it returns is a promise that resolves to an object of type MediaStream . When the promise successfully resolves, you can access the underlying media stream and perform any additional actions.
In our code, we are keeping things simple and just setting our stream to our video element’s srcObject property:
If there are any failures, the catch block will kick in.
Tip: Stopping the Webcam Stream
If you want to stop the webcam stream, you need some code that looks as follows:
This thread goes into more detail on what you should do along with a working example,
Conclusion
So, there you have it — a look at how you can access a user’s webcam video stream and display it in the browser. Once you get the video displayed, you can then do all sorts of things that you can do to videos in general. You can apply crazy filters, you can take a snapshot and save the image to disk, etc. I may cover some of these in future tutorials.
Got a question or just want to chat? Comment below or drop by our forums (they are actually the same thing!) where a bunch of the friendliest people you’ll ever run into will be happy to help you out!
THE KIRUPA NEWSLETTER
Get cool tips, tricks, selfies , and more. personally hand-delivered to your inbox!
( View past issues for an idea of what you’ve been missing out on all this time! )
Встраиваем трансляцию с веб-камеры в страницу браузера
На странице размещается HTML-код, который ссылается на несколько JavaScript файлов и других файлов (зависимостей). В результате web-страница может транслировать видео с веб-камеры и воспроизводить видео на странице с помощью HTML5 и Flash — технологий.
Подготовка к интеграции трансляции с веб-камеры в веб-страницу
Для организации трансляции из браузера Google Chrome или IE вам потребуется подготовить Web Call Server и необходимые скрипты и файлы
Установите Web Call Server на свой хостинг и импортируйте SSL-сертификаты для работы технологии WebRTC.
Если установка сервера вызывает у вас какие-либо затруднения, вы можете запустить готовый к работе и сконфигурированный виртуальный Web Call Server в облаке Amazon и импортировать SSL сертификат .
Кроме этого вы можете подключиться к нашим демо-серверам
Распакуйте сборку на вашем веб-сервере и откройте файлы
Эти файлы не требуют изменений и являются минимальным кодом, позволяющим транслировать видео с веб-камеры и воспроизводить видеопоток в браузерах Chrome, IE и других браузерах, работающих с WebRTC и Flash. Рассмотрим их ниже.
HTML и JavaScript код для встраивания трансляции с веб-камеры в веб-страницу
Опишем основные элементы скриптов Streaming-min.html и Streaming-min.js, которые используются в трансляции.
Streaming-min.html
Все необходимые зависимости расположены в HTML-элементе head
Далее идут видеоокна — элементы, которые будут отображать видео, захваченное с веб-камеры, а также полученное видео для воспроизведения.
Здесь localVideo — видео с веб-камеры, remoteVideo — окно воспроизведения видеопотока по технологии WebRTC, flashVideoDiv — блок, в который будет вставлен Flash(swf) объект для воспроизведения по технологии Flash.
Streaming-min.js
Основные функции скрипта: инициализация, установка соединения, публикация потока с веб-камеры и воспроизведение.
При инициализации указываются видео элементы и устанавливаются слушатели статусов.
Для установки соединения требуется адрес WCS-сервера, например wss://wcs5-eu.flashphoner.com:8443
Для публикации и воспроизведения требуется назначить / знать только имя видеопотока.
Файлы Streaming-min работают корректно и используют простой и минимальный код, но не отображают результаты своей работы, такие как статусы, названия потоков, состояние кнопок, и т.д. Для контроля работы этих примеров рекомендуется использовать Developer Tools / Console — инструмент для разработчиков, встроенный в браузер Google Chrome.
Немного более сложные примеры с отображением статусов потоков и переключением состояний кнопок можно найти в файлах: examples/demo/streaming , которые используются в демо-страницах в разделе Тестирование
Добавление Websocket-плеера
для браузера iOS Safari
Браузер Safari под управлением iOS в таких устройствах как iPhone и iPad не поддерживает технологию WebRTC и не может по этой причине использовать скрипты Streaming-min.
Для iOS Safari есть специальные скрипты плеера, который работает по технологии Websockets:
В этих скриптах похожим образом проходит инициализация, установка соединения и воспроизведение потока.
Есть две особенности, которые актуальны для мобильных браузеров:
- Чтобы звук начал проигрываться в динамике смартфона, пользователь должен нажать какую-нибудь кнопку или ссылку на HTML-странице, т.е. сделать клик по экрану смартфона. В примере этой кнопкой выступает Play.
При переключении между мобильными приложениями на iPhone или iPad воспроизведение должно вставать на паузу (операция mute). Для этого используется специальная callback-функция, которая называется visibilityHandler.
Для обслуживания потокового видео по протоколу Websocket во время инициализации подключается дополнительная зависимость WSReceiver и важно чтобы этот скрипт был доступен по указанному пути.
Таким образом, мы показали необходимые скрипты, необходимые для внедрения трансляций с веб-камеры в браузере. Вы можете использовать данные скрипты как базу для построения собственного пользовательского интерфейса. Протестировать работу демо-скриптов можно в разделе Т естирование
Эта страница скорее всего устарела
Загрузить Web Call Server 5
Системные требования: Linux x86_64, 1 core CPU, 2 Gb RAM, Java
Установка:
- wget https://flashphoner.com/download-wcs5.2-server.tar.gz
- Распаковать и установить с помощью скрипта ‘install.sh’
- Запустить сервер с помощью команды ‘service webcallserver start’
- Открыть веб-интерфейс https://host:8444 и активировать вашу лицензию
Если вы используете серверы Amazon EC2, то скачивать ничего не нужно.