forked from vueuse/vueuse
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
86 lines (74 loc) · 1.98 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import type { MaybeRef } from '@vueuse/shared'
import type { Ref } from 'vue-demi'
import { ref, shallowRef, watch } from 'vue-demi'
import { useSupported } from '../useSupported'
import type { ConfigurableNavigator } from '../_configurable'
import { defaultNavigator } from '../_configurable'
export interface UseDisplayMediaOptions extends ConfigurableNavigator {
/**
* If the stream is enabled
* @default false
*/
enabled?: MaybeRef<boolean>
/**
* If the stream video media constraints
*/
video?: boolean | MediaTrackConstraints | undefined
/**
* If the stream audio media constraints
*/
audio?: boolean | MediaTrackConstraints | undefined
}
/**
* Reactive `mediaDevices.getDisplayMedia` streaming
*
* @see https://vueuse.org/useDisplayMedia
* @param options
*/
export function useDisplayMedia(options: UseDisplayMediaOptions = {}) {
const enabled = ref(options.enabled ?? false)
const video = options.video
const audio = options.audio
const { navigator = defaultNavigator } = options
const isSupported = useSupported(() => navigator?.mediaDevices?.getDisplayMedia)
const constraint: DisplayMediaStreamConstraints = { audio, video }
const stream: Ref<MediaStream | undefined> = shallowRef()
async function _start() {
if (!isSupported.value || stream.value)
return
stream.value = await navigator!.mediaDevices.getDisplayMedia(constraint)
return stream.value
}
async function _stop() {
stream.value?.getTracks().forEach(t => t.stop())
stream.value = undefined
}
function stop() {
_stop()
enabled.value = false
}
async function start() {
await _start()
if (stream.value)
enabled.value = true
return stream.value
}
watch(
enabled,
(v) => {
if (v)
_start()
else
_stop()
},
{ immediate: true },
)
return {
isSupported,
stream,
start,
stop,
enabled,
}
}
export type UseDisplayMediaReturn = ReturnType<typeof useDisplayMedia>