Код:
<!DOCTYPE html>
<html>
<head>
<title>Live Test</title>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
</head>
<body>
<!-- Видео канвас -->
<video id="webcamera_livedemo" autoplay width="640px" height="480px"></video>
<br>
<!-- При нажатие выходим в лайв -->
<button id="btnGoLive">Go Live!</button>
<!-- При нажатие останавливаем лайв -->
<button id="btnStop" style="display:none;">Stop</button>
<script>
document.getElementById('btnGoLive').addEventListener('click', async function init(e) {
try {
// Получаем устройства, пользователь должен подтвердить
const objstream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true, width:1024, height:768 });
// Объект на видео поток
const carrVideoTracks = objstream.getVideoTracks();
// Объект на аудио поток
const carrAudiotracks = objstream.getAudioTracks();
// Высвечиваем alert что вышли онлайн
alert('Live:' + carrVideoTracks[0].label);
// Ретранслируем видео в тэг video
document.getElementById('webcamera_livedemo').srcObject = objstream;
document.getElementById('btnStop').addEventListener('click', function(e) {
// Если нажали на кнопку стоп, перестать стримить
carrVideoTracks[0].stop();
carrAudiotracks[0].stop();
document.getElementById('btnGoLive').setAttribute('style', 'display:block;');
document.getElementById('btnStop').setAttribute('style', 'display:none;');
});
document.getElementById('btnGoLive').setAttribute('style', 'display:none;');
document.getElementById('btnStop').setAttribute('style', 'display:block;');
} catch (error) {
// Если ошибка
alert(error.name);
console.error(error);
}
});
</script>
</body>
</html>