DEV Community


Ionic video call by peerjs

timsar2 profile image timsar2 ・4 min read

Before starting, this is ionic 5 angular 9 simple example of video call.
At the end you can connect two device if the app is running on both of them.
if you want to wake up the app first you have to use something like push notification, we don't implement it now.

let do it fast :D

ionic must be installed.

from your console run

ionic start ionic-peer blank

then inside of your project folder, get peerjs:

npm install peerjs --save

add esModuleInterop to your tsconfig.json as below:

"compilerOptions": {
    "esModuleInterop": true,

create peer service:

ionic generate service providers/webrtc

edit WebrtcService, it'll initiate peer-to-peer connection and make call.

import Peer from 'peerjs';

export class WebrtcService {
  peer: Peer;
  myStream: MediaStream;
  myEl: HTMLMediaElement;
  partnerEl: HTMLMediaElement;

  stun = '';
  mediaConnection: Peer.MediaConnection;
  options: Peer.PeerJSOption;
  stunServer: RTCIceServer = {
    urls: 'stun:' + this.stun,

  constructor() {

    this.options = {  // not used, by default it'll use peerjs server
      key: 'cd1ft79ro8g833di',
      debug: 3

  getMedia() {
    navigator.getUserMedia({ audio: true, video: true }, (stream) => {
    }, (error) => {

  async init(userId: string, myEl: HTMLMediaElement, partnerEl: HTMLMediaElement) {
    this.myEl = myEl;
    this.partnerEl = partnerEl;
    try {
    } catch (e) {
    await this.createPeer(userId);

  async createPeer(userId: string) {
    this.peer = new Peer(userId);
    this.peer.on('open', () => {

  call(partnerId: string) {
    const call =, this.myStream);
    call.on('stream', (stream) => {
      this.partnerEl.srcObject = stream;

  wait() {
    this.peer.on('call', (call) => {
      call.on('stream', (stream) => {
        this.partnerEl.srcObject = stream;

  handleSuccess(stream: MediaStream) {
    this.myStream = stream;
    this.myEl.srcObject = stream;

  handleError(error: any) {
    if ( === 'ConstraintNotSatisfiedError') {
      const v =;
     // this.errorMsg(`The resolution ${v.width.exact}x${v.height.exact} px is not supported by your device.`);
      this.errorMsg(`The resolution px is not supported by your device.`);
    } else if ( === 'PermissionDeniedError') {
      this.errorMsg('Permissions have not been granted to use your camera and ' +
        'microphone, you need to allow the page access to your devices in ' +
        'order for the demo to work.');
    this.errorMsg(`getUserMedia error: ${}`, error);

  errorMsg(msg: string, error?: any) {
    const errorElement = document.querySelector('#errorMsg');
    errorElement.innerHTML += `<p>${msg}</p>`;
    if (typeof error !== 'undefined') {

init method will create a peer connection with yourId and then register wait method to listen to any call .
if any call receive inside wait method, it'll answer the call automatically,
you can handel it by yourself
(new peer() without option will connect to default server, you can use other server or run your own peer server)
it'll also start to stream video/audio as you define in option and push it to object of html element.(we have to create a html element to show video in home.html page)

call method will ask peer server to connect you to your partner as call type.
both call method and wait method duty is streaming partner video/audio and show it inside of partner media frame(we will create it inside home page)

Edit home.html

  <div id="errorMsg"></div>

  <video id="partner-video" (click)="swapVideo('my-video')" autoplay playsinline
    [ngClass]="{'top-video': topVideoFrame === 'partner-video', 'main-video': topVideoFrame != 'partner-video'}">
  <video id="my-video" (click)="swapVideo('partner-video')" autoplay playsinline
    [ngClass]="{'top-video': topVideoFrame === 'my-video', 'main-video': topVideoFrame != 'my-video'}" >

  <ion-row nowrap>
    <ion-button (click)="init()">Login As: </ion-button>
      <ion-input type="text" [(ngModel)]="userId" placeholder="enter your nick name"></ion-input>

  <ion-row nowrap>
    <ion-button (click)="call()">Call To: </ion-button>
      <ion-input type="text" [(ngModel)]="partnerId" placeholder="your partner nick name"></ion-input>

video tag will show you stream media of you and your partner.
you have to login with nick name, because of using default server, you may see other people with easy nick name :D

Edit home.ts like this

import { WebrtcService } from '../providers/webrtc.service';

export class HomePage {
  topVideoFrame = 'partner-video';
  userId: string;
  partnerId: string;
  myEl: HTMLMediaElement;
  partnerEl: HTMLMediaElement;

    public webRTC: WebrtcService,
    public elRef: ElementRef
  ) {}

  init() {
    this.myEl = this.elRef.nativeElement.querySelector('#my-video');
    this.partnerEl = this.elRef.nativeElement.querySelector('#partner-video');
    this.webRTC.init(this.userId, this.myEl, this.partnerEl);

  call() {;

  swapVideo(topVideo: string) {
    this.topVideoFrame = topVideo;

login method will assign video frame to html element and pass them to webrtcservice, so the service can push stream to them.

call method will pass partnerId to webrtc service for connection to your partner.

Edit home.scss

    position: absolute;
    top: 100px;
    right: 100px;
    max-width: 100px;
    z-index: 2;

    width: 100%;
    max-height: 70%;

after you and your partner get connected, you can swap video with swapVideo method and [ngClass].

webrtc service will ask for camera/microphone permission.
because of that, when we run application outside of localhost, browser will block permission, so we have to run it with --ssl parameter.
first join your pc/laptop with your second device (pc/laptop or mobile) to the same network
then run ionic serve with your ip address, for example:

ionic serve --address --ssl

in your second device visit that address with https prefix:

source on github

That's it, i hope it's useful.


Editor guide
lautalopez profile image

how can i implement a webrtc backend server?

timsar2 profile image
timsar2 Author

Look at this repository
Good backend with signalr
And this:

You just need a signaling server
Each client should send his signal to other client
For doing this you need a server to swap client 's signal.
So used webrtc to create signal in both client and swap them with backend.
I used signalr and websocket
You can use any language and technic to swap signal between clients.

innovativethinkingptyltd profile image
Innovative Thinking

Are you available to provide a paid integration?

eestebanjjosue profile image

Hi, thanks for this awesome tutorial, I could make a basic videocall app, but I am facing a problem, in my phone when I make it an app the camera does not work, I can see the camera and audio in the other device(my pc). Sometimes I get an error "getUserMedia error: NotReadableError". Ant idea what could be wrong? If I use my android device as a second device and I connect to the app throug LAN it works.
P.D. The sound gets returned from the speakers of the pc so it makes that awful sound if I am not wearing headphones. Is there a way to fix this too?

travbradfield profile image

How do I end the call and close the video?

timsar2 profile image
timsar2 Author


gemdajs profile image
Nasirudeen Olawale

It will be helpful if you can share directives on how to make the app serve with ssl on (android) devices.

timsar2 profile image
timsar2 Author

I used same address then running android + Conveyore (an extension) for visual studio
to solve cors issue on local host
try something like this: ionic cordova run android --address --ssl

prosenjitbarui9 profile image
Prosenjit Barui

How to create room with peerjs so multi user can join that room

cacardinal profile image

Would this work with a Firebase WebRTC or does it require a Peerjs server?

timsar2 profile image
timsar2 Author

i didn't touch firebase webrtc, but webrtc client's just need a signaling server to swap their signale(created in client side).
you can also use simple peer and a signaling server

rvasquezz profile image

you are not using the default speaker! Can you change the default speaker and camera?

g_arikado profile image
Carlos Cortina

Those who want to eliminate the echo in the video call add to the ngOnInit:

const audioPlayer = document.getElementById('my-video');
audioPlayer.volume = 0;