iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍣

Build Your Own Clubhouse Clone with Agora

に公開
2021/08/14

I wasn't invited to Clubhouse, so I tried making it myself—that's the vibe here. Well, I don't really mind not being invited; I'm not that interested, it'll probably open up eventually anyway, and look, I use Android, so those grapes are probably sour anyway[1].

This is my first time trying this, and I'm writing this as I figure things out, so please feel free to send a PR if you notice anything.

Summary First

  • Apparently, Clubhouse uses Agora
  • Agora - Real-Time Voice and Video Engagement
  • Free tier includes 10,000 minutes of voice per month
    • (I previously mistakenly wrote "10,000 hours/month." It's minutes. My apologies.)
  • Official Tutorial: Start a Voice Call
  • Demo I built: ginpei/try-agora


10,000 free minutes every month. From the pricing page


Screenshot of the demo. Features a start button, participant ID list, etc.

Agora?

A service that provides APIs for audio and video streaming. It's pay-as-you-go, but there's a free tier of 10,000 voice minutes/month, which I could easily try out without registering a credit card. By the way, 10,000 minutes is roughly 7 days. That's generous.

The web SDK can be installed via CDN or npm install agora-rtc-sdk-ng. I'm happy to see they provide solid type definitions for TypeScript. Besides web, they offer a wide range of SDKs for iOS, Android, Unity, Flutter, React Native, and more.

And it seems the rumored Clubhouse is indeed running on this.

https://zenn.dev/voluntas/scraps/9403b803320d6f

  • The real-time delivery service being used is Agora.io
    • Just checked the DNS
    • Saw ap-japan.agora.io

Trying the Demo

I'm about to show you how to build it, but the finished product is available on GitHub. (Sorry, there's no live demo.)

  • ginpei/try-agora
    • Implementation starts from main() in public/main.js
    • Non-essential UI operations and such are implemented in ui.js

To try it out, clone the repository, then copy public/secrets.example.js to public/secrets.js and configure your settings. You'll need an Agora account and related information.

If you want to try talking with friends, I've provided npm run serve:proxy using ngrok to expose your localhost externally.

Screenshot of the demo. Start button, list of participant IDs, etc.

Let's Build It

This is for the web version (client-side JavaScript).

Creating an Account

First, create an Agora account and a project for your demo app. It's free.

You'll come back later to retrieve the necessary information.

A bit more

I don't think it was there the first time, but if you're asked to select an "Authentication Mechanism" when creating the project, choose "Secure mode." No token is a bit scary, right?


New project creation screen. It says "Testing mode" doesn't require a token.

After signing up, things proceed pretty smoothly like a tutorial, so I don't think you'll get stuck, but I saw another article that explains this in detail, so please check that as well if you'd like.

Creating the App Skeleton

Prepare an appropriate HTML file. I will assume you have it ready and can display it in your browser.

Loading the SDK

In this demo, I wrote it in plain JavaScript. The server is also very simple, using Browsersync. The library is delivered via CDN, so let's use that for now.

<script src="https://download.agora.io/sdk/release/AgoraRTC_N-4.3.0.js"></script>

If you prefer, you can mix it into React or something similar. In that case, use the npm package.

$ npm install agora-rtc-sdk-ng
import AgoraRTC from "agora-rtc-sdk-ng"

Preparing the Client

Implementation starts here.

First, create an instance of the client that connects to the Agora server.

const client = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });

Keep this client object, as you will be using it throughout the process.

Interaction

We will handle 4 types of user operations and 4 types of notifications from Agora.

For user operations, please prepare the following buttons in your HTML. Then, use button.onclick and so on.

  • join - Join the channel
  • leave - Leave the channel
  • publish - Start audio transmission (unmute)
  • unpublish - Stop audio transmission (mute)

Notifications from Agora can be monitored with client.on(). We will use the following events:

  • user-joined - Someone joined
  • user-left - Someone left
  • user-published - Someone started publishing
  • user-unpublished - Someone stopped publishing

So, it looks like this. We will create the callback functions next.

document.querySelector("#join").onclick = onJoinClick;
document.querySelector("#leave").onclick = onLeaveClick;
document.querySelector("#publish").onclick = onPublishClick;
document.querySelector("#unpublish").onclick = onUnpublishClick;

client.on("user-joined", onAgoraUserJoined);
client.on("user-left", onAgoraUserLeft);
client.on("user-published", onAgoraUserPublished);
client.on("user-unpublished", onAgoraUserUnpublished);

Joining a Channel

async function onJoinClick() {
  const uid = await client.join(appId, channel, token, null);
}

Now, you need four values. Please find them in the Agora console > Project Management.

How to find the values
  • appId - The one labeled "App ID"
  • channel - This can be whatever you like. It seems you can use spaces and symbols (refer to the join() API specifications).
  • token - Something generated based on the channel and other info.
    • Generate it via Project Management > Edit > Features > Generate temp token
    • Since Secure mode is usually selected during project creation, this is practically required.
  • uid - Set to null to have it generated automatically.

When generating the token, enter the channel name you will use, such as demo_channel_name, exactly. If they don't match, you'll get a CAN_NOT_GET_GATEWAY_SERVER error.


Generating a temp token. Enter the channel name.

Note that while you can generate a token from the console for a demo, you should generate it yourself in production. This is because you need to use the secret App certificate. It cannot be done on the client side where the code is exposed. Do it on the server side or with something serverless.

Leaving a Channel

client.localTracks is an array that will grow later when publishing.

async function onLeaveClick() {
  // Close the audio track (required)
  client.localTracks.forEach((v) => v.close());

  await client.leave();
}

The audio track will be created in the next onPublishClick() step.

It is mandatory to close this audio track when leaving. While it's not specifically mentioned in the API description, if you don't close it properly, something seems to persist (implementation not confirmed); for example, the recording icon that Chrome displays in the tab remained active. (I wonder if we don't need to call client.unpublish()?)

Destroying the local media tracks is mandatory. You can follow your own implementation preferences.

Anyway, you can now join and leave a channel. If you just want to listen, you're done here.

Starting Audio Transmission

Starting to speak.

async function onPublishClick() {
  const localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
  await client.publish([localAudioTrack]);
}

Stopping Audio Transmission

Muting your own audio.

async function onUnpublishClick() {
  await client.unpublish();
}

By the way, it seems you can register multiple audio tracks with publish() and specify which one to close in the unpublish() argument. If omitted, all tracks will be closed. I wonder how this relates to leave()?

I'm not entirely sure, but maybe it's better to call client.localTracks.forEach((v) => v.close()) at this timing too.

Anyway, you can now handle your own operations. From here, we'll retrieve audio from other people.

Someone Joined

You should do something like display them in the participant list. (In the demo code, the list is actually updated here.)

// client.on("user-joined", onAgoraUserJoined);

async function onAgoraUserJoined(user) {
}

user: IAgoraRTCRemoteUser has the following properties:

  • audioTrack
  • hasAudio
  • hasVideo
  • uid
  • videoTrack

Handling user names or icon images is outside the scope of Agora, so you'll need to map those yourself. Since the user.uid here matches the return value of that person's client.join(), you could store it in Redis when they join.

Someone Left

// client.on("user-left", onAgoraUserLeft);

async function onAgoraUserLeft(user, reason) {
}

There are 3 types of reason:

  • "Quit" - They left
  • "ServerTimeOut" - They went offline
  • "BecomeAudience" - Their role changed to audience

role is not covered in this article.

Someone Published

They started talking, so let's listen.

// client.on("user-published", onAgoraUserPublished);

async function onAgoraUserPublished(user, mediaType) {
  const track = await client.subscribe(user, mediaType);
  track.play();
}

Someone Unpublished

// client.on("user-unpublished", onAgoraUserUnpublished);

async function onAgoraUserUnpublished(user, mediaType) {
}

It seems you don't particularly need to manipulate the audio track with close() or similar.

By the way, in the tutorial, they curiously try to delete a <div> here, but since we haven't created such a thing and haven't confirmed it, it will cause an error. I wonder if that was a step in an older version of the API?

Anyway, you can now hear other people's voices, and the voice chat is complete. Success!

Troubleshooting

Errors when loading the screen

AgoraRTCError NOT_SUPPORTED: enumerateDevices() not supported.

AgoraRTCError WEB_SECURITY_RESTRICT: Your context is limited by web security, please try using https protocol or localhost.

→ Open the URL with localhost or https://. You will get this error with http://.

Errors when joining a channel

AgoraRTCException
AgoraRTCError CAN_NOT_GET_GATEWAY_SERVER: dynamic use static key

→ Provide a string for the token instead of setting it to null. The documentation says string | null, but it's practically required.

AgoraRTCError INVALID_PARAMS: Invalid token: . If you don not use token, set it to null

→ Set the token in secrets.js. It's currently an empty string.

Choose server https://webrtc2-ap-web-1.agora.io/api/v1 failed, message: AgoraRTCError CAN_NOT_GET_GATEWAY_SERVER: dynamic key expired, retry: false

→ Regenerate the token. It has expired. Lasts about 24 hours?

AgoraRTCError CAN_NOT_GET_GATEWAY_SERVER: invalid token, authorized failed

→ Check if the token was generated with the correct channel name.

How to get a token

Here:

Or follow this documentation: Generate a Token

Error when starting audio transmission

AgoraRTCError INVALID_OPERATION: Can't publish stream, haven't joined yet!

→ Call client.join() first.

Error when someone leaves

TypeError: Cannot read property 'remove' of null

→ Check if the element exists.

The documentation tells you to remove the element resulting from document.getElementById(user.uid), but no matter how much I look through the documentation, such an element isn't actually being created.

Recording icon won't disappear

→ Ensure client.localTracks.forEach((v) => v.close()) is executed. It really was mandatory.

Too many log outputs

For now, you can hide them by placing something like -[INFO] -[DEBUG] in the DevTools console filter.

The End

Now you can build your own Clubhouse clone. All that's left is to add login controls and polish the UI. Agora is easy and has a generous free tier, so it could be interesting to integrate it into other apps. Video too.

Go build the ultimate Clubhouse of your own!

References

脚注
  1. The Fox and the Grapes - Wikipedia ↩︎

Discussion