Want to develop your own video chat app? But, not sure where to start? Don’t worry at all! We are here with a tutorial that will help you build your own video chat application. Don’t limit yourself, and start exploring with us!
Here, we will learn with the Twilio video chat example and build a one-to-one video chat application with Twilio, Rails, and Javascript. With this application, you can easily video chat with your family and friends.
Before building the Twilio video chat app with Rails, look at the video below to have a rough idea of the demo. The video chat app development will consist of three major sections:
Before getting started with the Twilio video chat example, here’s the system set up-
Create a new rails application using the below commands
Then, run the following command to install dependencies – bootstrap, jQuery, and popper.js
After this, add the following code in the config/webpack/environment.js file.
const { environment } = require('@rails/webpacker') const webpack = require("webpack") environment.plugins.append("Provide", new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', Popper: ['popper.js', 'default'] })) module.exports = environment
Go to app/assets/stylesheets/application.css and add the following line above the require_tree and require_self lines.
And add this code in application.js
Now, it’s time to create a Model, View, and Controller using Scaffold once we have a basic setup. Use the below command to do the same.
After that, go to the migration file and add the unique_name and room_sid field to the migration. We will use this in the future. Now your migration will look like this.
After that, migrate the database using.
Go to the config/routes.rb file and add the root path for your app.
After that, go to this URL http://localhost:3000/.
Congratulations! If you see this screen, your app is working.
Looking for an enthusiastic team of ROR developers to shape the vision of your web project?
Bacancy is a one-stop solution for custom app development. Contact us today and hire Ruby on Rails developer from us for your dream project.
Now let’s create the random string as a unique name for each room. Add this code to the room.rb model.
before_create :add_uniqe_name def add_uniqe_name unless self.unique_name.present? self.unique_name = (0...15).map { ('a'..'z').to_a[rand(26)] }.join end end
This will create a unique random string for the unique_name field whenever a new room is generated.
Moving on further with the tutorial to build a video chat application with Twilio, Rails, and JS. Here, we are done with creating a room. Now, let’s set up a Twilio account and store its credentials.
For that, we are going to use Twilio Programmable video. For this, we need a Twilio account. Click here to create an account if you don’t have any.
After that, go to your Twilio dashboard and copy the ACCOUNT SID and AUTH TOKEN.
For storing credentials, we are going to use dotenv. Create a .env file in the root directory of the project. And Add the following line in config/application.rb.
For this tutorial, I’m going to create that file in the twilio-video-call folder. If you use git for version control, don’t forget to add this file in gitignore.
Go to the API Key section and click the red plus sign to create a new API key. Give your key a recognizable name representing the project you’re working on in the Friendly Name text field and leave the Key Type Standard. Click the button that says Create API Key. Assign those keys to API_KEY_SID and API_KEY_SECRET.
Add those credentials in the .env file.
Now, it’s the logic time! Let’s get our rooms together and code some logic.
Change the Show action’s code with the following code.
// controllers/rooms_controller.rb def show @client = Twilio::REST::Client.new(ENV['ACCOUNT_SID'], ENV['AUTH_TOKEN']) unless @room.room_sid.present? # create room in twilio twilio_room = @client.video.rooms.create(type: 'peer-to-peer',unique_name: @room.unique_name) @room.update(room_sid: twilio_room.sid) end identity = (0...5).map { ('a'..'z').to_a[rand(26)] }.join @room_name = @room.unique_name #create token to access Twilio room @token = Twilio::JWT::AccessToken.new(ENV['ACCOUNT_SID'], ENV['API_KEY_SID'],ENV['API_KEY_SECRET'], identity: identity) #create video grant for token grant = Twilio::JWT::AccessToken::VideoGrant.new grant.room = @room_name @token.add_grant grant @token = @token.to_jwt end
This code will first check the presence of sid (unique id used for Twilio unique rooms) in the database. If it is not available, it will generate the room in Twilio and store the sid in the database.
We are creating a unique string as a unique identifier for the Twilio room. (You can use the logged-in user’s name for it.)
It will create the Twilio token and video grant.
For building a user interface, open views/rooms/show.html.erb and use the below code. You can change the styling part as you like.
Visit app/assets/stylesheets/rooms.scss for styling your application.
Let’s write the code for connecting Twilio rooms.
Include the Twilio js in the show.html.erb file
<%= javascript_include_tag 'https://media.twiliocdn.com/sdk/js/video/releases/2.3.0/twilio-video.min.js' %>
Create a video_call.js file in the javascript/packs folder and include that file from application.js. And add the following code in that file.
window.joinRoom = async function(room, token){ const Video = Twilio.Video; const localTracks = await Video.createLocalTracks({ audio: true, video: { height: 1080, frameRate: 24, width: 1980 }, }); try { room = await Video.connect(token, { name: room, tracks: localTracks, bandwidthProfile: { video: { mode: 'collaboration', maxTracks: 10, dominantSpeakerPriority: 'high', renderDimensions: { high: {height:1080, width:1980}, standard: {height:720, width:1280}, low: {height:176, width:144} } } }, dominantSpeaker: true, maxAudioBitrate: 16000, preferredVideoCodecs: [{ codec: 'VP8', simulcast: true }], networkQuality: {local:1, remote: 4} }); } catch (error) { console.log(error); } const localMediaContainer = document.getElementById("local-video"); localTracks.forEach((localTrack) => { localMediaContainer.appendChild(localTrack.attach()); }); // display video/audio of other participants who have already joined room.participants.forEach(onParticipantConnected); room.on("participantConnected", onParticipantConnected); room.on("participantDisconnected", onParticipantDisconnected); $("#call-end-btn").removeClass("d-none"); $("#call-end-btn").on("click",function() { onLeaveButtonClick(room); }) }; window.onParticipantConnected = function(participant){ var remote_div = document.getElementById('remote-video'); const participantDiv = document.createElement('div'); participantDiv.id = participant.sid; const trackSubscribed = (track) => { participantDiv.appendChild(track.attach()); }; participant.on("trackSubscribed", trackSubscribed); participant.tracks.forEach((publication) => { if (publication.isSubscribed) { trackSubscribed(publication.track); } }); remote_div.appendChild(participantDiv); const trackUnsubscribed = (track) => { track.detach().forEach((element) => element.remove()); }; participant.on("trackUnsubscribed", trackUnsubscribed); }; window.onParticipantDisconnected = function(participant){ const participantDiv = document.getElementById(participant.sid); participantDiv.parentNode.removeChild(participantDiv); }; window.onLeaveButtonClick = function(room){ room.localParticipant.tracks.forEach((publication) => { const track = publication.track; track.stop(); const elements = track.detach(); elements.forEach((element) => element.remove()); }); room.disconnect(); window.location = '/'; };
This function will generate the local video and audio track and publish it in the Twilio cloud for the specific room using a token. And display your local video in DOM. It will do the same for other remote users of the same room and display the remote user’s video in your DOM.
When you click on the disconnect button, It will remove your video locally and from the Twilio room and redirect you to the index page.
Now call this function from your show page of the room. Add the below code in views/rooms/show.html.erb
Now go to your root path and create a room. After that, go to the show page of that room and wait 3-4 sec while Twilio js is loaded from CDN. Copy that URL and paste it into the incognito tab, and Here we go. Your video call app is ready.
The entire source code is available here: twilio-video-chat-app. Feel free to clone the repo and play around with it.
I hope the Twilio video chat tutorial was helpful, and you have decided to build your video chat application with Twilio, Rails, and JS. If you’re a ROR enthusiast, then the ROR tutorials page is for you! Visit the Ruby on Rails tutorials page and start learning with Bacancy. Write to us if you have any questions or suggestions.
Sometimes you need experienced and skilled developers to handle requirements and bottlenecks for you. Do you want to lessen your struggles? Are you looking for proficient ROR developers for hassle-free app development? Then contact us now and hire ROR developer.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.