I created a media component, so in the ngAfterViewInit()
I do the following:
...
@ViewChild('video')
public video: ElementRef;
private stream: any;
...
public ngAfterViewInit() {
const constraints = {
audio: false,
video: {
width: { min: 1024, ideal: 1280, max: 1920 },
height: { min: 776, ideal: 720, max: 1080 },
facingMode: 'environment'
}
};
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(constraints).then(stream => {
this.video.nativeElement.src = window.URL.createObjectURL(stream);
this.stream = stream;
this.video.nativeElement.play();
}).catch(function(err) {
this.logger.error(err.name + ': ' + err.message);
});
} else {
this.logger.error('Your browser does not support the mediaDevices API');
}
}
Note: I don’t need audio and I want to use the rear facing camera.
In the ngOnDestroy()
I do the following:
public ngOnDestroy() {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
if (this.stream) {
this.video.nativeElement.pause();
this.video.nativeElement.src = '';
this.stream.getTracks().forEach( track => track.stop() );
}
}
}
The Component’s template:
selector: 'page-media',
template: `
<div id="media-container">
<div id="media">
<video #video id="video" muted playsinline autoplay></video>
</div>
</div>`
And, the Component’s .scss:
page-media {
#media-container {
background-color: black;
max-width: 1920px;
}
#media {
width: 100%;
}
#video {
width: 100%;
}
}
The Page’s markup:
<ion-content no-bounce class="media-container">
<ion-grid>
<ion-row align-items-center>
<page-media>
</page-media>
</ion-row>
</ion-grid>
</ion-content>
The Page’s .scss:
.media-container {
.scroll-content {
background-color: black !important;
display: flex;
flex-direction: column;
overflow: hidden;
}
ion-grid {
padding: 0;
height: 100%;
}
ion-row {
flex: 1;
}
}