uni-app vue3 小程序接入 aliyun-rtc-wx-sdk

安裝依賴:

npm install aliyun-rtc-wx-sdk crypto-js

uni-app,新建一個頁面,粘貼以下代碼
在阿里云實時音視頻補充appId、appKey即可,

<template><view class="container"><!-- 用戶輸入區域 --><view class="input-section" v-if="!isJoined"><uni-easyinputv-model="channelId"placeholder="請輸入頻道ID":clearable="true"/><uni-easyinputv-model="userName"placeholder="請輸入用戶名":clearable="true"/><uni-easyinputv-model="userId"placeholder="請輸入用戶ID":clearable="true"/><button @click="joinChannel" type="primary">加入房間</button></view><!-- 直播控制區域 --><view class="control-section" v-if="isJoined"><button @click="leaveChannel" type="warn">離開房間</button><button @click="switchCamera">切換攝像頭</button><button @click="toggleMic">{{ pusher.enableMic ? '關閉麥克風' : '開啟麥克風' }}</button><button @click="toggleCamera">{{ pusher.enableCamera ? '關閉攝像頭' : '開啟攝像頭' }}</button></view><!-- 推流組件 --><live-pusher ref="livePusher":url="pusher.url" :mode="pusher.mode" :autopush="pusher.autopush" :beauty="pusher.beauty":whiteness="pusher.whiteness" :muted="pusher.muted" :mirror="pusher.mirror" :local-mirror="pusher.localMirror":enable-camera="pusher.enableCamera" :enable-mic="pusher.enableMic" :remote-mirror="pusher.remoteMirror":enable-ans="pusher.enableAns" :device-position="pusher.devicePosition" :enable-agc="pusher.enableAgc"@statechange="onPusherStateChange" @netstatus="onPusherNetStatus" @error="onPusherError"style="width: calc((100vw - 40rpx)); height: calc((100vw - 40rpx)/4*3);" v-if="pusher.url" />拉流組件列表({{ playerList.length }}):<view class="player-list" v-if="playerList.length > 0"><view v-for="(player, index) in playerList" :key="index" class="player-item"><live-player :src="player.src" mode="RTC" autoplay @statechange="onPlayerStateChange" @netstatus="onPlayerNetStatus"style="width: calc((50vw - 25rpx)); height: calc((50vw - 25rpx)/4*3);" /><text>{{ player.userName || player.userId }}</text></view></view><!-- 調試信息 --><view class="debug-info"><text>房間狀態: {{ isJoined ? '已加入' : '未加入' }}</text><text>用戶數量: {{ playerList.length }}</text></view></view>
</template><script setup lang="ts">
import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import { queryAndGetUserInfo, UserInfo, getUserInfo } from '@/utils/userInfo'
import * as MainApi from './mainApi'
import baseInfo from '@/utils/base'
import { pagesRecords } from '@/hooks/pageRecordsHooks'// live-pusher  實例,用于切換攝像頭
let LivePusher = uni.createLivePusherContext('livePusher')import AliRtcEngine from "aliyun-rtc-wx-sdk";
import CryptoJS from 'crypto-js';pagesRecords()let currentInstance = ref()
const { ctx } = getCurrentInstance() as any// 響應式數據
const pusher = ref({})
const playerList = ref([])
const isJoined = ref(false)
const userName = ref('')
const userId = ref('')
const appId = ref('')
const appKey = ref('')
const channelId = ref('AliRtcDemo')let artc: any = null// 生成Token
const generateToken = (appId: string, appKey: string, channelId: string, userId: string, timestamp: number) => {const data = `${appId}${appKey}${channelId}${userId}${timestamp}`;const hash = CryptoJS.SHA256(data);return hash.toString(CryptoJS.enc.Hex);
}// 初始化ARTC引擎
const initARTC = async () => {try {artc = AliRtcEngine.getInstance()bindEvents()uni.showToast({title: 'ARTC引擎初始化成功',icon: 'success'})} catch (error) {console.error('ARTC引擎初始化失敗:', error)uni.showToast({title: 'ARTC引擎初始化失敗',icon: 'error'})}
}// 綁定事件監聽
const bindEvents = () => {// 遠程用戶上線通知artc.on("remoteUserOnLineNotify", (user: any, newPlayerList: any[]) => {		uni.showToast({title: `${user.displayName || user.userId} 加入了房間`,icon: "none",})playerList.value = newPlayerList})// 遠程用戶下線通知artc.on("remoteUserOffLineNotify", (user: any, newPlayerList: any[]) => {uni.showToast({title: `${user.displayName || user.userId} 退出了房間`,icon: "none",})playerList.value = newPlayerList})// 遠程軌道可用通知artc.on("remoteTrackAvailableNotify", (user: any, newPlayerList: any[]) => {playerList.value = newPlayerList})// 被踢出房間artc.on("bye", () => {uni.showToast({title: "您已被踢出房間",icon: "none",})pusher.value = {}playerList.value = []isJoined.value = false})
}// 加入頻道
const joinChannel = async () => {if (isJoined.value) {uni.showToast({title: '已在房間中',icon: 'none'})return}// 檢查用戶輸入if (!userName.value.trim()) {uni.showToast({title: '請輸入用戶名',icon: 'none'})return}if (!userId.value.trim()) {uni.showToast({title: '請輸入用戶ID',icon: 'none'})return}uni.showLoading({title: '加入房間中...'})try {const timestamp = Math.floor(Date.now() / 1000) + 3600const token = generateToken(appId.value, appKey.value, channelId.value, userId.value, timestamp)const { pusherAttributes, playerList: newPlayerList } = await artc.joinChannel({appId: appId.value,appKey: appKey.value,channelId: channelId.value,userId: userId.value,userName: userName.value,token: token,timestamp: timestamp}, userName.value)pusher.value = pusherAttributesplayerList.value = newPlayerListisJoined.value = true// 開始推流artc.getPusherInstance().start()uni.hideLoading()uni.showToast({title: '加入房間成功',icon: 'success'})} catch (error) {uni.hideLoading()console.error('加入房間失敗:', error)uni.showToast({title: '加入房間失敗',icon: 'error'})}
}// 離開頻道
const leaveChannel = async () => {if (!isJoined.value) {return}try {await artc.leaveChannel()pusher.value = {}playerList.value = []isJoined.value = falseuni.showToast({title: '已離開房間',icon: 'success'})} catch (error) {console.error('離開房間失敗:', error)}
}// 切換攝像頭
const switchCamera = () => {LivePusher.switchCamera()
}// 切換麥克風
const toggleMic = () => {pusher.value.enableMic = !pusher.value.enableMic
}// 切換攝像頭
const toggleCamera = () => {pusher.value.enableCamera = !pusher.value.enableCamera
}// live-pusher 狀態變化處理
const onPusherStateChange = (e: any) => {console.log("live-pusher code: ", e.detail.code)artc.handlePusherStateChange(e)
}// live-pusher 網絡狀態處理
const onPusherNetStatus = (e: any) => {console.log("live-pusher netStatus: ", e.detail.info)artc.handlePusherNetStatus(e)
}// live-pusher 錯誤處理
const onPusherError = (e: any) => {artc.handlePusherError(e)
}// live-player 狀態變化處理
const onPlayerStateChange = (e: any) => {console.log("live-player code: ", e.detail.code)artc.handlePlayerStateChange(e)
}// live-player 網絡狀態處理
const onPlayerNetStatus = (e: any) => {console.log("live-player netStatus: ", e.detail.info)artc.handlePlayerNetStatus(e)
}// 生命周期
onMounted(() => {initARTC()
})onUnmounted(() => {leaveChannel()
})
</script><style scoped lang="scss">
.container {padding: 20rpx;
}.input-section {margin-bottom: 30rpx;.uni-easyinput {margin-bottom: 20rpx;}button {margin-top: 20rpx;}
}.control-section {display: flex;flex-wrap: wrap;gap: 10rpx;margin-bottom: 30rpx;button {font-size: 24rpx;flex: 1;padding: 0;}
}.player-list {display: flex;flex-wrap: wrap;gap: 10rpx;margin-top: 30rpx;.player-item {text-align: center;text {display: block;margin-top: 10rpx;font-size: 24rpx;color: #666;}}
}.debug-info {margin-top: 30rpx;padding: 20rpx;background-color: #f5f5f5;border-radius: 10rpx;text {display: block;margin-bottom: 10rpx;font-size: 24rpx;color: #333;}
}
</style>

userName、userId隨便寫,不重復即可,想進入同一個頻道就讓channelId一致,

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/94692.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/94692.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/94692.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java技術棧/面試題合集(3)-Java并發篇

場景 Java入門、進階、強化、擴展、知識體系完善等知識點學習、性能優化、源碼分析專欄分享: Java入門、進階、強化、擴展、知識體系完善等知識點學習、性能優化、源碼分析專欄分享_java高級進階-CSDN博客 通過對面試題進行系統的復習可以對Java體系的知識點進行查漏補缺。…

[AI 生成] Spark 面試題

spark 基礎問題面試題以下是 Spark 基礎面試題的全面梳理&#xff0c;涵蓋核心概念、架構原理和編程模型&#xff0c;幫助快速掌握高頻考點&#xff1a;一、核心概念1. Spark 核心組件組件作用Driver執行 main() 方法&#xff0c;調度任務&#xff0c;管理集群資源Executor在 W…

MySQL的DML增刪改操作:

目錄 添加數據&#xff1a; 方式1&#xff1a;一條一條添加數據&#xff1a; 方式2&#xff1a;將查詢結果插入到表中&#xff1a; 更新數據&#xff1a; 刪除數據&#xff1a; MySQL8的新特性&#xff1a;計算列&#xff1a; 本文介紹了MySQL數據庫操作語言(DML)的基本使…

MySQL運維常用語法速查

&#x1f5c3;? 一、數據庫操作 CREATE DATABASE db_name; USE db_name; DROP DATABASE db_name; SHOW DATABASES;&#x1f517; 官方文檔 &#x1f4ca; 二、表操作 表創建示例 CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(50) NOT NULL,email V…

汽車以太網通信協議——SOME/IP

1. 背景 SOME/IP是一種汽車中間件解決方案&#xff0c;其全稱是Scalable Service-Oriented Middleware over IP&#xff0c;即位于 IP 協議層以上的一種面向服務的可擴展的中間件。 中間件&#xff1a;該術語起源于復雜的軟件系統開發&#xff0c;用以實現軟件組件之間的數據交…

什么是負載均衡,有哪些常見算法?

文章目錄1.什么是負載均衡2.負載均衡的分類2.1 二層負載均衡2.2 三層負載均衡2.3 四層負載均衡2.4 七層負載均衡3.負載均衡工具3.1 LVS3.2 Nginx3.3 HAProxy4.常見負載均衡算法5.面試回答模板1.什么是負載均衡 為了提升web應用的各方面能力&#xff0c;我們一般會把多臺機器組…

PyTorch 核心三件套:Tensor、Module、Autograd

歡迎來到啾啾的博客&#x1f431;。 記錄學習點滴。分享工作思考和實用技巧&#xff0c;偶爾也分享一些雜談&#x1f4ac;。 有很多很多不足的地方&#xff0c;歡迎評論交流&#xff0c;感謝您的閱讀和評論&#x1f604;。 目錄引言1 Tensor1.1 &#x1f6e0;?Tensor 的核心用…

python源碼是如何運行起來的

為什么要了解底層原理 寫出高質量代碼 問題定位 滿足好奇心 機械通感 開始 當我們編寫并運行一行 print(Hello, World!) 時&#xff0c;背后究竟發生了什么&#xff1f;Python 代碼是如何從我們可讀的文本&#xff0c;變成計算機可以執行的指令的呢&#xff1f; 很多人將…

MacOS Docker 安裝指南

MacOS Docker 安裝指南 引言 Docker 是一個開源的應用容器引擎,它允許開發者打包他們的應用以及應用的依賴包到一個可移植的容器中,然后發布到任何流行的 Linux 機器上,也可以實現虛擬化。容器是完全使用沙箱機制,相互之間不會有任何接口(類似 iPhone 的 app)。Docker …

Cisco 3750X交換機更新到IOS 15.2后無法啟動 提示:Boot process failed...

背景及故障現象 一臺新購入的二手Cisco 3750X-48P&#xff0c;原機自帶IOS軟件版本為12.x&#xff0c;可以正常工作。 但將IOS版本升級到15.2之后&#xff0c;在啟動過程中卡住。 第一次加載IOS軟件時是正常的&#xff0c;提示&#xff1a; Loading "flash:/c3750e-uni…

Redis Redis 常見數據類型

Redis 提供了 5 種數據結構&#xff0c;理解每種數據結構的特點對于 Redis 開發運維非常重要&#xff0c;同時掌握每種數據結構的常見命令&#xff0c;會在使用 Redis 的時候做到游刃有余。 一、預備知識 官方文檔&#xff1a;Commands | Docs (redis.io) 1、最核心的兩個命令…

金融風控實戰:Spring Boot + LightGBM 貸款預測模型服務化(超詳細版)

金融風控實戰&#xff1a;Spring Boot LightGBM 貸款預測模型服務化&#xff08;超詳細版&#xff09;一、整體架構設計二、模型訓練與優化1. 特征工程&#xff08;Python&#xff09;2. 模型評估與優化三、Spring Boot 服務實現1. 項目結構2. ONNX 模型服務3. 特征工程服務4.…

前端學習 7:EDA 工具

目錄 EDA 工具 Design Ware Synopsys CoreTools 套件 VCS verdi Design Compiler EDA 工具 常用的EDA工具主要來自三家公司&#xff1a;Synopsys、Cadence和Mentor&#xff08;已被Siemens收購&#xff09;。EDA&#xff0c;全稱電子設計自動化&#xff08;Electronics …

windows有一個企業微信安裝包,腳本執行并安裝到d盤。

以下是將本地已有的企業微信安裝包安裝到D盤的完整PowerShell腳本&#xff0c;包含詳細的錯誤處理和進度反饋&#xff1a; <# .SYNOPSIS使用本地企業微信安裝包安裝到D盤 .DESCRIPTION自動檢測本地安裝包&#xff0c;靜默安裝到指定目錄支持.exe和.msi格式安裝包 #># 強制…

[LVGL] 布局系統 lv_flex, lv_grid | 輸入設備 lv_indev | union

第五章&#xff1a;布局系統&#xff08;lv_flex, lv_grid&#xff09; 歡迎回來&#xff01; 在第四章&#xff1a;樣式&#xff08;lv_style&#xff09;中&#xff0c;我們掌握了如何通過色彩、字體和圓角等特性美化部件。當界面元素具備視覺吸引力后&#xff0c;如何優雅…

Linux中的mkdir命令

基本語法mkdir 命令的基本語法如下&#xff1a;mkdir [選項] 目錄名創建單個目錄要創建一個新目錄&#xff0c;只需在 mkdir 后跟上目錄名稱。例如&#xff1a;mkdir new_folder這會在當前工作目錄下創建一個名為 new_folder 的目錄。創建多個目錄可以一次性創建多個目錄&#…

基于大數據的美食視頻播放數據可視化系統 Python+Django+Vue.js

本文項目編號 25003 &#xff0c;文末自助獲取源碼 \color{red}{25003&#xff0c;文末自助獲取源碼} 25003&#xff0c;文末自助獲取源碼 目錄 一、系統介紹二、系統錄屏三、啟動教程四、功能截圖五、文案資料5.1 選題背景5.2 國內外研究現狀 六、核心代碼6.1 查詢數據6.2 新…

微信小程序精品項目-基于springboot+Android的計算機精品課程學習系統(源碼+LW+部署文檔+全bao+遠程調試+代碼講解等)

博主介紹&#xff1a;??碼農一枚 &#xff0c;專注于大學生項目實戰開發、講解和畢業&#x1f6a2;文撰寫修改等。全棧領域優質創作者&#xff0c;博客之星、掘金/華為云/阿里云/InfoQ等平臺優質作者、專注于Java、小程序技術領域和畢業項目實戰 ??技術范圍&#xff1a;&am…

(五)系統可靠性設計

2024年博主考軟考高級系統架構師沒通過&#xff0c;于是決定集中精力認真學習系統架構的每一個環節&#xff0c;并在2025年軟考中取得了不錯的成績&#xff0c;雖然做信息安全的考架構師很難&#xff0c;但找對方法&#xff0c;問題就不大&#xff01; 本文主要是博主在學習過程…

Shuffle SOAR使用學習經驗

Shuffle SOAR 1. 基礎操作與配置1.1 環境搭建與系統要求1.1.1 硬件與操作系統要求Shuffle SOAR 平臺作為一款開源的安全編排、自動化與響應&#xff08;SOAR&#xff09;工具&#xff0c;其部署方式靈活&#xff0c;支持云端和自托管兩種模式。對于自托管部署&#xff0c;官方推…