Created
August 5, 2018 04:50
-
-
Save imaustink/a4645f4185c9dac692b8317a30aed498 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const ViewModel = DefineMap.extend({ | |
// Default resolution of media constraints | |
height: { | |
type: 'number', | |
default: 1080 | |
}, | |
width: { | |
type: 'number', | |
default: 1920 | |
}, | |
// Getter that builds and returns a media constraints object | |
get constraints () { | |
const { | |
selectedVideoDevice, | |
selectedAudioDevice, | |
height, | |
width | |
} = this | |
const video = selectedVideoDevice ? { | |
deviceId: { | |
exact: selectedVideoDevice | |
}, | |
height, | |
width | |
} : false | |
const audio = selectedAudioDevice ? { | |
deviceId: { | |
exact: selectedAudioDevice | |
} | |
} : false | |
return { | |
video, | |
audio | |
} | |
}, | |
// The device selected video device ID | |
selectedVideoDevice: { | |
type: 'string' | |
}, | |
// The device selected audio device ID | |
selectedAudioDevice: { | |
type: 'string' | |
}, | |
// A filtered list of all video devices | |
get videoDevices () { | |
const videoDevices = this.devices.filter(device => device.kind === 'videoinput') | |
if (videoDevices.length) { | |
this.selectedVideoDevice = videoDevices[0].deviceId | |
} | |
return videoDevices | |
}, | |
// A filtered list of all audio devices | |
get audioDevices () { | |
const audioDevices = this.devices.filter(device => device.kind === 'audioinput') | |
if (audioDevices.length) { | |
this.selectedAudioDevice = audioDevices[0].deviceId | |
} | |
return audioDevices | |
}, | |
// A list of all devices | |
devices: { | |
type: 'observable', | |
default () { | |
return [] | |
} | |
}, | |
// The preview media stream | |
previewStream: { | |
Type: MediaStream | |
}, | |
// Setup and teardown | |
// This is called when the component is inserted into the DOM | |
connectedCallback () { | |
const deviceChangeHandler = () => { | |
navigator.mediaDevices.enumerateDevices() | |
.then(devices => (this.devices = devices)) | |
.catch(error => console.error(error)) | |
} | |
deviceChangeHandler() | |
navigator.mediaDevices.addEventListener('devicechange', deviceChangeHandler) | |
this.listenTo('constraints', (event, constraints) => { | |
if (constraints.video || constraints.audio) { | |
navigator.mediaDevices.getUserMedia(constraints) | |
.then(stream => (this.previewStream = stream)) | |
.catch(error => console.error(error)) | |
} | |
}) | |
// This is called when the component is removed from the DOM | |
return () => { | |
navigator.mediaDevices.removeEventListener('devicechange', deviceChangeHandler) | |
this.stopListening() | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment