纯JS实现WebRTC点对点视频通话用于学习WebRTC

1. 页面代码主要的实现逻辑

先看页面代码,这里使用的webRTC浏览器原生的API。目前信令服务器使用的是Java SpringBoot WebSocket实现的。这里是在内网环境下测试,如果在公网环境中测试还需要配置STUN\TURN服务器,在代码iceServers处配置。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>video</title>
</head>
<body>
<h2 style="text-align: center;">播放页面</h2>
<h3 id="userId" style="text-align: center;"></h3>
<center>
    <div>
        <video id="localVideo" class="video" autoplay="autoplay"></video>
        <video id="remoteVideo" class="video" height="500px" autoplay="autoplay"></video>
    </div>
</center>
</br>
<div style="text-align: center;">
    <button id="callBtn" onclick="requestConnect()">建立连接</button>
    <button id="hangupBtn" onclick="hangupHandle()">断开连接</button>
</div>
</br>
<div style="text-align: center;">
    对方id: <input id="toUserId">
</div>
</body>
</html>
<script src="./adapter-latest.js"></script>
<script>
    const localVideo = document.querySelector('#localVideo');
    const remoteVideo = document.querySelector('#remoteVideo');

    const callBtn = document.getElementById('callBtn')
    const hangupBtn = document.getElementById('hangupBtn')

    const config = {
     
     
        iceServers: [
            {
     
      urls: 'stun:global.stun.twilio.com:3478?transport=udp' }
        ],
    };

    let peerConnection;

    let socket, userId, toUserId;
    userId = parseInt(Math.random()*10000);
    document.getElementById('userId').innerText = '我的id:' + userId;

    // 本地流和远端流
    let localStream, remoteStream;

    function requestConnect() {
     
     
        toUserId = document.getElementById('toUserId').value
        if(!toUserId){
     
     
            alert(
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值