Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3 webrtc

作者:★执着唯她   发布日期:2025-05-01   浏览:70

// main.js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

// App.vue
<template>
  <div id="app">
    <h1>Vue3 WebRTC Example</h1>
    <video id="localVideo" autoplay playsinline></video>
    <video id="remoteVideo" autoplay playsinline></video>
    <button @click="startCall">Start Call</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      localStream: null,
      peerConnection: null,
      configuration: {
        iceServers: [
          {
            urls: 'stun:stun.l.google.com:19302',
          },
        ],
      },
    };
  },
  methods: {
    async startCall() {
      try {
        this.localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
        document.getElementById('localVideo').srcObject = this.localStream;

        this.peerConnection = new RTCPeerConnection(this.configuration);

        this.localStream.getTracks().forEach((track) => {
          this.peerConnection.addTrack(track, this.localStream);
        });

        this.peerConnection.ontrack = (event) => {
          if (event.streams && event.streams[0]) {
            document.getElementById('remoteVideo').srcObject = event.streams[0];
          }
        };

        // Create an offer and set it as the local description
        const offer = await this.peerConnection.createOffer();
        await this.peerConnection.setLocalDescription(offer);

        console.log('Offer created:', offer);

        // For simplicity, we are not handling signaling here.
        // In a real application, you would send the offer to the other peer via a signaling server.
      } catch (error) {
        console.error('Error starting call:', error);
      }
    },
  },
};
</script>

<style>
#app {
  text-align: center;
}

video {
  width: 400px;
  margin: 10px;
}
</style>

解释说明

  1. main.js: 这是 Vue 3 的入口文件,创建并挂载了根组件 App.vue
  2. App.vue:
    • 模板部分: 包含两个视频元素 (localVideoremoteVideo) 和一个按钮 (Start Call)。点击按钮会触发 startCall 方法。
    • 脚本部分:
      • data: 定义了一些用于存储本地流、对等连接和配置的对象。
      • methods:
        • startCall: 获取用户的媒体流(摄像头和麦克风),并将流设置为本地视频元素的源。然后创建一个新的 RTCPeerConnection 并将本地流添加到该连接中。当接收到远程流时,将其设置为远程视频元素的源。最后创建并设置本地描述符(offer)。
    • 样式部分: 简单的样式设置,使视频元素居中并设置宽度。

请注意,这个示例代码没有处理信令(signaling)部分,实际应用中需要通过信令服务器来交换 SDP 和 ICE 候选者信息。

上一篇:vue3跳转页面传递参数

下一篇:vue 打开新窗口

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站