Commit 9d138982 authored by huanglu's avatar huanglu

feat: 直播

parent e81524e4
......@@ -32,6 +32,9 @@ module.exports = {
'eol-last': 0,
'object-curly-spacing': 0,
'padded-blocks': 0,
'no-trailing-spaces': 0
'no-trailing-spaces': 0,
'import/no-unresolved': 0,
'import/no-named-as-default-member': 0,
'no-underscore-dangle': 0
},
};
This diff is collapsed.
......@@ -15,9 +15,13 @@
"lint": "vue-cli-service lint"
},
"dependencies": {
"@geek/geekui": "^1.1.2",
"axios": "^0.19.2",
"core-js": "^3.6.4",
"crypto-js": "^4.0.0",
"element-ui": "^2.13.1",
"hrtc": "file:sdk/RTC-WebRTCSDK_2.0.0.tar.gz",
"socket.io-client": "2.x",
"vue": "^2.6.11",
"vue-router": "^3.1.6",
"vuex": "^3.1.3"
......@@ -57,4 +61,4 @@
},
"description": "极客双师项目",
"author": "黄露"
}
\ No newline at end of file
}
<template>
<div id="app">
<gk-header />
<keep-alive>
<router-view v-if="$route.meta.keepAlive"/>
</keep-alive>
......@@ -10,9 +9,8 @@
<script>
import { mapMutations } from 'vuex';
import { login, userinfo } from '@/api';
import {GkHeader} from '@/components'
// import { mapMutations } from 'vuex';
// import { login, userinfo } from '@/api';
export default {
data() {
......@@ -20,20 +18,17 @@ export default {
name: 'sfsfs'
}
},
components: {
GkHeader
},
mounted() {
login('huanglu', '123').then((res) => {
console.log(res);
});
userinfo({ id: '2424' }).then((res) => {
console.log('userinfo ----> ', res);
});
// login('huanglu', '123').then((res) => {
// console.log(res);
// });
// userinfo({ id: '2424' }).then((res) => {
// console.log('userinfo ----> ', res);
// });
},
methods: {
...mapMutations(['changeName']),
// ...mapMutations(['changeName']),
},
};
</script>
......
This diff is collapsed.
import videoPlay from './video_play.png'
import videoBg from './video_bg.png'
import nocontent from './nocontent.png'
import bg from './bg.png'
export {
videoPlay,
videoBg,
nocontent
}
\ No newline at end of file
nocontent,
bg
}
<template>
<div class="geek-rtc-play" ref="player"></div>
</template>
<script>
export default {
components: {},
props: {
stream: {
type: Object
}
},
data() {
return {
};
},
watch: {
stream: {
handler(N, O) {
if (N !== O) this.createPlayer();
}
}
},
methods: {
createPlayer() {
const id = this.stream && this.stream.getId()
if (id) {
if (this.$refs.player) {
this.uid = id
const player = document.createElement('div')
player.setAttribute('id', id);
player.style.height = '100%'
player.style.width = '100%'
this.$refs.player.innerHTML = ''
this.$refs.player.appendChild(player)
this.stream.play(id, { muted: false, objectFit: 'contain' })
}
}
}
},
mounted() {
this.createPlayer(this.stream)
}
}
</script>
<style lang="scss" scoped>
.geek-rtc-play {
height: 100%;
width: 100%;
}
</style>
// eslint-disable-next-line import/no-named-as-default
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '@/views/home';
const Cart = () => import('@/views/cart');
// 直播房间
const OnlineRoom = () => import('@/views/online')
// 答题
const AnswerScreen = () => import('@/views/answer-screen')
// 老师画板
const PainScreen = () => import('@/views/paint-screen')
// 大屏
const DashScreen = () => import('@/views/big-screen')
Vue.use(VueRouter);
......@@ -10,13 +18,28 @@ Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'Home',
name: 'online-room',
component: OnlineRoom
},
{
path: '/home',
name: 'home',
component: Home
},
{
path: '/cart',
name: 'Cart',
component: Cart
path: '/paint',
name: 'paint',
component: PainScreen
},
{
path: '/ans-screen',
name: 'ans-screen',
component: AnswerScreen
},
{
path: '/big-screen',
name: 'big-screen',
component: DashScreen
}
];
......
/* eslint-disable no-unused-expressions */
/* eslint-disable class-methods-use-this */
import {
ErrorCode, RtcError, LogLevel, Logger, ClientConfig, Client, StreamConfig, Stream, HRTC
} from 'hrtc'
import CryptoJS from 'crypto-js/crypto-js'
export default class HWOnline {
/** 询问浏览器的摄像头和麦克风权限 */
static getAuthUserMedia() {
return new Promise((r) => {
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia
|| navigator.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true,video: true}, () => {
r(true)
}, (err) => {
r(false)
})
} else {
r(false)
}
})
}
constructor(userId, appId = '5fd31c330a67e1333c498ef8', domain = '5fd31c330a67e1333c498ef8.cloudrtc.myhuaweicloud.com') {
this.appId = appId
this.userId = userId
this.domain = domain
HRTC.setLogLevel('error')
this.streams = []
this.joinedUsers = []
this.createClient();
this.addStreamEvent();
}
// static publish get
/** version */
rtcVersion = () => HRTC.VERSION
/** devices */
getDevices = () => HRTC.getDevices()
/** cameras */
getCameras = () => HRTC.getCameras()
/** microphones */
getMicrophones = () => HRTC.getMicrophones()
/** 是否支持屏幕分享 */
isScreenShareSupported = () => HRTC.isScreenShareSupported()
/** 检测浏览器是否兼容SDK */
isMatchHWSDK = () => HRTC.checkSystemRequirements()
/** 创建客户端 */
createClient = () => {
const { appId, domain } = this;
const client = HRTC.createClient({
appId,
domain
});
this.client = client;
}
joinRoom(roomId) {
const ctimeDst = 7200000
const ctime = Math.floor((ctimeDst + new Date().getTime()) / 1000).toString()
const message = `${this.appId}+${roomId}+${this.userId}+${ctime}`
return this._joinRoom(roomId, {
userId: this.userId,
role: 0,
ctime,
userName: `${this.userId}`,
signature: CryptoJS.HmacSHA256(message, this.appId).toString(),
})
}
leaveRoom() {
this.localStream && this.localStream.close()
this.client && this.client.leave()
}
/**
* 加入房间
* @param {*} client 客户端实例
* @param {*} roomId 房间id
* @param {*} option
* userId:本端用户唯一标识
* userName:用户昵称。
* signature:鉴权签名字串,应用开发者需要向远端服务器获取鉴权签名。
* ctime:签名时间戳。
* role: 用户角色,可以标识媒体方向,取值如下:
* 0: joiner(发布并观看)
* 1: publisher(只发布不观看)
* 2: player(只观看不发布)
*/
async _joinRoom(roomId, option) {
return new Promise((r, e) => {
this.client.join(roomId, option).then((res) => {
r(res)
}).catch((error) => {
e(error)
})
})
}
/** 创建本地流并发布 */
createStream = async (microphoneId, cameraId) => {
const stream = HRTC.createStream({
audio: !!microphoneId,
microphoneId,
video: !!cameraId,
cameraId,
});
stream.setScreenProfile({
width: 1920,
height: 1080
});
await stream.initialize()
await this.publish(stream)
this.localStream = stream;
// stream.play(this.elId,{ muted: false, objectFit: 'contain' }) // 播放本地流
return stream
}
// 创建屏幕共享流
async createScreenShareStream() {
const supported = this.isScreenShareSupported()
if (!supported) {
try {
// eslint-disable-next-line no-underscore-dangle
const stream = await this._startCapture({ audio: true, video: true, peerIdentity: true })
this.screenStream = HRTC.createStream({
videoSource: stream.getVideoTracks()[0],
audioSource: stream.getAudioTracks()[0],
});
this.screenStream.setScreenProfile({
width: 1980,
height: 1080,
});
await this.screenStream.initialize()
await this.publish(this.screenStream)
} catch (error) {
if (this.screenStream) {
this.screenStream.close()
}
}
}
}
publish(stream) {
this.client.publish(stream)
}
playStream() {
}
addStreamEvent() {
// 远端流添加事件
this.client.on('stream-added', (event) => {
console.log('stream-added: ', event)
const {stream} = event
this.client.subscribe(stream, { video: true, audio: true})
})
// 远端流删除事件,当取消选看远端用户或者原来已经选看的远端用户退出房间后会收到该事件通知。
this.client.on('stream-removed', (event) => {
const {stream} = event
const index = this.streams.findIndex((itm) => itm.getId() === stream.getId())
if (index > -1) {
this.streams.splice(index, 1)
}
this.subscribedCb && this.subscribedCb(this.streams);
})
// 远端流更新事件,当远端用户的流发生变化,例如添加或者移除音视频轨,视频轨规格变化时会收到该事件通知。
this.client.on('stream-updated', (event) => {
const {stream} = event
this.client.subscribe(stream, { video: true, audio: true})
})
// 远端用户加入房间
this.client.on('peer-join', (user) => {
console.log('peer-join : ', user)
this.joinedUsers.push(user)
this.joinCb && this.joinCb(user, this.joinedUsers)
})
// 远端用户离开房间
this.client.on('peer-leave', (user) => {
console.log('peer-leave', user)
// eslint-disable-next-line no-unused-expressions
this.joinedUsers = this.joinedUsers.filter((itm) => `${itm.userId}` !== `${user.userId}`)
this.joinCb && this.joinCb(user, this.joinedUsers)
})
// 远端流订阅/选看成功事件。
this.client.on('stream-subscribed', (event) => {
const {stream} = event
console.log('stream-subscribed: ', this.streams)
console.log('stream-subscribed: ', stream, stream.getId(), this.userId, stream.getUserId())
const index = this.streams.findIndex((itm) => itm.getId() === stream.getId())
if (index <= -1) {
this.streams.push(stream)
}
// eslint-disable-next-line no-unused-expressions
this.subscribedCb && this.subscribedCb(this.streams);
})
}
// 订阅流后的回调
subscribedStreamCb(cb) {
this.subscribedCb = cb
}
// 有用户加入房间的回调
userJoinCb(cb) {
this.joinCb = cb
}
// 有用户加入房间的回调
userLeaveCb(cb) {
this.usrLeaveCb = cb
}
// eslint-disable-next-line no-underscore-dangle
async _startCapture(displayMediaOptions) {
let captureStream = null;
try {
captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
} catch (err) {
Promise.reject(err)
}
return captureStream;
}
}
import io from 'socket.io-client'
import axios from 'axios'
const socketUrl = 'http://192.168.32.53:7001/'
const http = axios.create({
baseURL: socketUrl,
timeout: 1500
})
let skt = null
let resListeners = []
let msgListeners = []
const connect = (userId, cb) => {
const socket = io(socketUrl, {
query: {
userId,
},
transports: ['websocket']
})
socket.on('connect', (client) => {
console.log('client: ', client)
// eslint-disable-next-line no-unused-expressions
cb && cb(socket.id);
})
socket.on('disconnect', (data) => {
console.log('disconnect:', data)
})
// 接收在线用户信息
socket.on('res', (msg) => {
console.log('消息回执', msg);
// eslint-disable-next-line no-use-before-define
resListeners.forEach((item) => {
// eslint-disable-next-line no-unused-expressions
item && item(msg)
})
});
socket.on('msg', (msg) => {
console.log('接收消息', msg);
msgListeners.forEach((item) => {
// eslint-disable-next-line no-unused-expressions
item && item(msg)
})
});
skt = socket
}
const onRes = (cb) => {
const data = resListeners.find((item) => cb === item)
// eslint-disable-next-line no-unused-expressions
cb && !data && resListeners.push(cb)
}
const onMsg = (cb) => {
const data = msgListeners.find((item) => cb === item)
console.log('data',data)
// eslint-disable-next-line no-unused-expressions
cb && !data && msgListeners.push(cb)
console.log('msgListeners',msgListeners)
}
const offRes = (cb) => {
const data = resListeners.filter((item) => cb !== item)
// eslint-disable-next-line no-const-assign
resListeners = data
}
const offMsg = (cb) => {
const data = msgListeners.filter((item) => cb !== item)
console.log('data====',data)
// eslint-disable-next-line no-const-assign
msgListeners = data
}
const sendMsg = (target, payload) => {
skt.emit('msg', {
target,
payload
})
}
const sendGroupMsg = (payload) => {
skt.emit('msg',{from: skt.id,...payload})
}
const on = (name, cb) => {
skt.on(name, cb)
}
const createRoom = (groupId, groupName) => {
http.post('/socket/createroom', {
groupId,
groupName,
socketId: (skt && skt.id) || ''
}).then((data) => {
console.log(data)
}).catch((error) => {
console.log('create room error: ', error)
})
}
const joinRoom = (groupId,cb) => {
console.log('socket id: ', skt.id)
http.post('/socket/joinroom', {
groupId,
socketId: (skt && skt.id) || ''
}).then((data) => {
// eslint-disable-next-line no-unused-expressions
cb && cb(data)
}).catch((error) => {
console.log('create room error: ', error)
})
}
const queryRooms = () => {
http.get('/socket/queryRooms', {
}).then((data) => {
console.log(data)
}).catch((error) => {
console.log('queryRooms room error: ', error)
})
}
const isConnect = () => skt.connected
export default {
connect,
sendMsg,
on,
isConnect,
createRoom,
joinRoom,
queryRooms,
sendGroupMsg,
onRes,
onMsg,
offRes,
offMsg
}
<template>
<div class="about">
<h1>This is an about page</h1>
<el-button type="primary">ss</el-button>
</div>
</template>
<script>
import { get } from '@/utils/request'
export default {
mounted() {
get('hello', {}).then((re) => {
console.log('===hello===', re)
})
}
}
</script>
<template>
<div class="gk-screen-std">
<div class="ans-wrap">
<el-button v-for="itm in Answers"
@click="chooseAnswer(itm.value)"
:key="itm.value" type="primary"
:class="['ans-itm', itm.value === currentAns ? 'ans-itm-select': '' ]">
{{itm.title}}
</el-button>
</div>
<el-button type="primary" :disabled="currentAns.length <= 0" class="ans-commit">提交</el-button>
</div>
</template>
<script>
const Answers = [
{ title: 'A', value: 'A' },
{ title: 'B', value: 'B' },
{ title: 'C', value: 'C' }
]
export default {
data() {
return {
Answers,
currentAns: '',
}
},
methods: {
chooseAnswer(value) {
console.log(value)
this.currentAns = value
}
}
}
</script>
<style lang="scss" scoped>
.gk-screen-std {
height: 100vh;
width: 100vw;
display: flex;
flex-flow: column;
align-items: center;
.ans-wrap {
margin-top: 20vh;
width: 100%;
text-align: center;
.ans-itm {
font-size: 40px;
width: 20vw;
height: 20vh;
margin: 10px 30px;
}
.ans-itm-select {
background-color: green;
}
}
.ans-commit {
font-size: 40px;
margin-top: 20vh;
}
}
</style>
<template>
<div class="gk-big-screen">
<div id='gk-big-screen-player'>
<RTCPlayer :stream="playStream" />
</div>
</div>
</template>
<script>
import HWRTC from '@/utils/hwrtc'
import RTCPlayer from '@/components/rct-play'
export default {
components: {
RTCPlayer
},
data() {
return {
playStream: null
};
},
methods: {
},
async mounted() {
const { userId } = this.$route.query
console.log('mounted')
// eslint-disable-next-line no-underscore-dangle
const ok = await HWRTC.getAuthUserMedia()
if (!ok) {
this.$alert('无摄像头和和麦克风权限');
return;
}
this.rtc = new HWRTC(userId || (new Date().getTime() / 1000).toFixed(0));
await this.rtc.joinRoom('123')
this.rtc.subscribedStreamCb((streams) => {
const stream = streams.find((itm) => itm.getUserId().includes('teacher'))
console.log('=======: ', streams)
if (stream) this.playStream = stream;
})
}
}
</script>
<style lang="scss" scoped>
.gk-big-screen {
height: 100vh;
width: 100vw;
#gk-big-screen-player {
height: 100%;
width: 100%;
}
}
</style>
<template>
<div class='cartpage'>
<h1 v-for="item in carts" :key="item.id">
{{ JSON.stringify(item) }}
</h1>
<div>
<el-button type="primary" @click="addCartInpage">add</el-button>
<button @click="deleteOne">deleteOne</button>
<button @click="deleteCartInpage">deleteAll</button>
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
name: 'cart',
// import引入的组件需要注入到对象中才能使用
components: {
},
data() {
// 这里存放数据
return {
};
},
computed: {
...mapState({
carts: (state) => state.cart.carts,
}),
},
watch: {},
methods: {
...mapActions(['cart/addCart', 'cart/deleteAll', 'cart/deleteCart']),
addCartInpage() {
if (!this.addIndex) this.addIndex = 1;
this['cart/addCart']({ id: this.addIndex, cart: 'sfshfksfhs' });
this.addIndex += 1;
},
deleteCartInpage() {
if (!this.deleteIndex) {
this.deleteIndex = 1;
}
this['cart/deleteAll'](this.deleteIndex);
this.deleteIndex += 1;
},
deleteOne() {
}
},
created() {
},
mounted() {
},
};
</script>
<style lang='scss' scoped>
</style>
<template>
<div class="home">
home page
</div>
<div class="gk-online-home">
<div class="content">
<h2 class="title">极客数学帮在线课堂</h2>
<el-form ref="form" label-width="90px">
<el-row :gutter="10">
<el-col :span="24">
<el-form-item label="输入房间号">
<el-input class="input" v-model="roomId" placeholder="请输入房间号" type="number"></el-input>
</el-form-item>
</el-col>
<el-col :span="24">
<el-form-item label="房间名">
<el-input class="input" v-model="roomName" placeholder="请输入房间名"></el-input>
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="10">
<el-col :span="24">
<el-radio-group v-model="joinType">
<el-radio-button v-for="itm in joinTypes"
:key="itm.value" :label="itm.title"></el-radio-button>
</el-radio-group>
</el-col>
</el-row>
</el-form>
<el-row style="margin-top: 40px">
<el-col :span="24">
<el-button type="primary" @click="join" style="width: 100%">进入</el-button>
</el-col>
</el-row>
</div>
</div>
</template>
<script>
import socket from '@/utils/socket'
const joinTypes = [
{title: '学生大屏', value: 'student', path: 'big-screen'},
{title: '老师课件', value: 'teacher', path: 'paint'},
// 老师预览的效果应该和学生的效果一样
{title: '老师预览', value: 'teacher-pre', path: 'big-screen'},
{title: '普通直播', value: 'online', path: 'online-room'},
{title: '学习答题', value: 'student-ans', path: 'ans-screen'},
]
export default {
components: {},
data() {
return {
value: '',
show: true,
output: '',
}
},
name: 'Home',
components: {
roomId: '',
roomName: '',
joinType: '学生大屏',
joinTypes
};
},
methods: {
// show() {
// this.$message({
// type: 'info',
// message: 'this is message',
// });
// },
join() {
const joinObj = this.joinTypes.find((itm) => itm.title === this.joinType)
let userId = null
if (joinObj.value.includes('teacher')) {
userId = `teacher-${new Date().getTime()}`
} else {
userId = `${new Date().getTime()}`
}
const routeName = joinObj.path
socket.connect(userId, () => {
socket.joinRoom('teacherid', () => {
this.$router.push({ name: routeName, query: { userId }})
})
})
}
},
};
mounted() {
}
}
</script>
<style scoped>
.home {
padding: 5px;
<style lang="scss" scoped>
.gk-online-home {
background: url(~@/assets/images/bg.png) no-repeat;
background-size: 100% 100%;
background-origin: border-box;
height: 100vh;
width: 100vw;
position: relative;
color: white;
.content {
padding: 30px;
position: absolute;
top: 50%; left: 70%; transform: translateX(-50%) translateY(-50%);
width: 500px;
height: 400px;
background: rgba(47, 79, 109, 0.4);
border-radius: 10px;
.title {
text-align: center;
margin: 10px 0;
}
.input {
color: white;
}
}
::v-deep .el-form-item__label {
color: white;
font-size: 15px;
}
}
</style>
<template>
<div class="home">
<div class="player">
<RtcPlayer :stream="localStream" class="local-player" />
<el-button v-if="isJoin" type="primary"
@click.native="fullPlayer" class="full-screen">全屏</el-button>
</div>
<div class="side">
<el-form ref="form" label-width="80px" style="margin-top: 30px">
<el-row :gutter="8">
<el-col :span="24">
<el-form-item label="房间号">
<el-input v-model="roomId" placeholder="Please input roomid" type='number'></el-input>
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="8">
<el-col :span="24">
<el-form-item label="麦克风">
<el-select style="width: 100%" v-model="microId" placeholder="选择麦克风">
<el-option v-for="itm in micro" :key="itm.deviceId"
:label="itm.label" :value="itm.deviceId"></el-option>
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="8">
<el-col :span="24">
<el-form-item label="摄像头">
<el-select style="width: 100%" v-model="camerId" placeholder="选择摄像头">
<el-option v-for="itm in cameras" :key="itm.deviceId"
:label="itm.label" :value="itm.deviceId"></el-option>
</el-select>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div class="operation">
<el-button type="primary" @click="play">加入房间</el-button>
</div>
</div>
<div class="stream-pre">
<RtcPlayer class="item" v-for="(itm, index) in streams" :stream="itm" :key="index" />
</div>
</div>
</template>
<script>
// eslint-disable-next-line import/no-unresolved
import HWRTC from '@/utils/hwrtc'
import RtcPlayer from '@/components/rct-play'
export default {
data() {
return {
value: '',
show: true,
output: '',
rtc: null,
roomId: null,
micro: [],
microId: '',
cameras: [],
camerId: '',
streams: [],
localStream: null,
isJoin: false
}
},
name: 'Home',
components: {
RtcPlayer
},
watch: {
microId(N, O) {
if (N !== O && this.isJoin) this.localStream.switchDevice('audio', N);
},
camerId(N, O) {
if (N !== O && this.isJoin) this.localStream.switchDevice('video', N);
}
},
methods: {
async play() {
try {
await this.rtc.joinRoom(this.roomId)
this.localStream = await this.rtc.createStream(this.microId, this.camerId)
// this.localStream.play('player', { muted: false, objectFit: 'contain' })
this.isJoin = true
} catch (error) {
console.log('创建失败: ', error)
}
},
join() {
this.rtc.joinRoom(this.roomId)
},
fullPlayer() {
console.log('full')
document.querySelector('#player').requestFullscreen()
}
},
async mounted() {
console.log('mounted')
// eslint-disable-next-line no-underscore-dangle
const ok = await HWRTC.getAuthUserMedia()
if (!ok) {
this.$alert('无摄像头和和麦克风权限');
return;
}
this.rtc = new HWRTC((new Date().getTime() / 1000).toFixed(0));
this.cameras = await this.rtc.getCameras()
this.micro = await this.rtc.getMicrophones()
console.log(this.cameras, this.micro)
this.rtc.subscribedStreamCb((streams) => {
this.streams = streams
console.log('******: ', streams)
})
},
beforeDestroy() {
// eslint-disable-next-line no-unused-expressions
this.isJoin && this.rtc.leaveRoom();
this.isJoin = false
}
};
</script>
<style lang='scss' scoped>
.home {
box-sizing: border-box;
display: flex;
flex-flow: row;
height: 100vh;
position: relative;
.side {
width: 20vw;
}
.stream-pre {
position: absolute;
top: 10px;
left: 0;
width: calc(100% - 20vw);
overflow: auto;
display: flex;
flex-flow: row;
.item {
margin-left: 10px;
width: 300px;
height: 220px;
}
}
.operation {
text-align: center;
}
.player {
position: relative;
flex: 1;
box-sizing: border-box;
border: 1px solid #f5f5f5;
.local-player {
height: 100%;
width: 100%;
}
.full-screen {
position: absolute;
top: 5px;
right: 10px;
z-index: 999;
}
}
}
</style>
<template>
<div class="paint-main" ref="pain_main">
<img :src="videoBg" class="bg"/>
<geek-draw-board ref="draw" :paintType="paintType" class="draw-board" />
<div class="tools-wrap">
<el-button class="itm" type="info" @click="changeTool(itm.title)"
v-for="itm in paintTypes" :key="itm.title">{{ itm.name }}</el-button>
</div>
<div class="stream-wrap">
<el-button class="itm" type="text" @click="steamAction(itm.title)"
v-for="itm in streamTypes" :key="itm.title">{{ itm.name }}</el-button>
</div>
<el-dialog title="推流设置"
width="400px"
:visible.sync="modal">
<el-form label-width="80px">
<el-form-item label="摄像头">
<el-select v-model="camera" placeholder="选择摄像头">
<el-option v-for="itm in cameras"
:key="itm.deviceId" :label="itm.label" :value="itm.deviceId"></el-option>
</el-select>
</el-form-item>
<el-form-item label="麦克风">
<el-select v-model="mico" placeholder="选择麦克风">
<el-option v-for="itm in micros"
:key="itm.deviceId" :label="itm.label" :value="itm.deviceId"></el-option>
</el-select>
</el-form-item>
</el-form>
<p style="text-align: center">
<el-button type="primary" @click="modal = false">确定</el-button>
</p>
</el-dialog>
</div>
</template>
<script>
import { GeekDrawBoard } from '@geek/geekui'
import Vue from 'vue'
import { videoBg } from '@/assets/images/index'
import HWRTC from '@/utils/hwrtc'
const paintTypes = [
{ title: 'pencil', name: '铅笔', width: 20 },
{ title: 'redo', name: '撤回' },
{ title: 'erase', name: '橡皮擦', width: 50 },
{ title: 'clear', name: '清空' },
]
const streamTypes = [
{ title: 'publish', name: '开始推流' },
{ title: 'unpublish', name: '停止推流' },
{ title: 'setting', name: '设置' },
{ title: 'full', name: '全屏' }
]
Vue.use(GeekDrawBoard)
export default {
components: {
},
data() {
return {
videoBg,
paintType: '',
paintTypes,
streamTypes,
micros: [],
mico: '',
cameras: [],
camera: '',
modal: false,
rtc: null
};
},
methods: {
changeTool(title) {
if (title === 'redo' || title === 'clear') {
// eslint-disable-next-line no-unused-expressions
this.$refs.draw && this.$refs.draw[title]();
return
}
this.paintType = title
},
async steamAction(action) {
if (action === 'setting') {
this.modal = true
}
if (action === 'publish') {
this.rtc.createScreenShareStream()
}
// if (action === 'unpublish') {
// }
if (action === 'full') {
// eslint-disable-next-line no-unused-expressions
this.$refs.pain_main && this.$refs.pain_main.requestFullscreen();
}
}
},
async mounted() {
this.paintType = 'pencil'
const ok = await HWRTC.getAuthUserMedia()
if (!ok) {
this.$alert('无摄像头和和麦克风权限');
return;
}
this.rtc = new HWRTC(`teacher${(new Date().getTime() / 1000).toFixed(0)}`);
this.cameras = await this.rtc.getCameras()
this.camera = (this.cameras[0] || {}).deviceId
this.micros = await this.rtc.getMicrophones()
await this.rtc.joinRoom('123')
this.isJoin = true
this.mico = (this.micros[0] || {}).deviceId
}
}
</script>
<style lang="scss" scoped>
.paint-main {
box-sizing: border-box;
height: 100vh;
width: 100vw;
position: relative;
.bg {
height: 100vh; width: 100vw;
}
.draw-board {
position: absolute;
box-sizing: border-box;
top: 0; left: 0;
width: 100vw;
height: 100vh;
}
.tools-wrap {
position: fixed;
left: 20px;
top: 50%;
transform: translateY(-50%);
display: flex;
flex-flow: column;
align-items: center;
.itm {
display: inline-block;
font-size: 12px;
width: 70px;
margin-top: 10px;
margin-left: 0;
}
}
.stream-wrap {
position: fixed;
top: 5px;
right: 5px;
}
}
</style>
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment