joinVoice() function
@irtio/client 5.0BrowsersThe joinVoice() function starts voice for a room connection: it joins the voice server with the router’s token, plays the speakers the room picks for this player and returns a Voice. It’s exported by @irtio/client/voice.
Syntax
joinVoice(room)
joinVoice(room, options)
Parameters
room- A
RoomClient: the connection whose voice to join. optionsOptional-
An object with any of these properties:
position- A function called with a player ID that returns where that player is, as an object with numbers
x,yand optionallyz, orundefined, which makes that speaker silent. Without it, every speaker plays at full volume, unpanned, as on a call, andspatialandrangedo nothing. spatial- A boolean. If
true, speakers are panned in 3D with Web Audio, played through one<audio>element, since Chrome’s echo cancellation ignores audio played straight from Web Audio. Iffalse, each speaker plays through its own<audio>element, its volume falling with distance. Defaults tofalse. range- A number: the distance at which a speaker falls silent, in the units
positionreturns. Volume falls linearly from 1 at distance 0. Defaults to 20.
Return value
A Voice.
Exceptions
None.
Description
The voice follows the room connection: it leaves the voice server when the connection drops, joins again with the new token after the reconnect, and ends when the connection closes for good. It doesn’t turn the microphone on: call enableMic() from a click, since browsers grant the microphone only from a user gesture.
Without the project’s voice setting, the router sends no token and joinVoice() does nothing. The room decides who hears whom, and RoomClient.peers holds that decision whether or not the client joins voice.
@irtio/client/voice is a separate entry, and it loads livekit-client, about 570 KB minified. Import it dynamically once the game has connected or the player opts in, so it loads in a chunk of its own; see the Client section of Proximity voice.
Examples
Hearing nearby players in a plaza
Each player hears the others by distance, placed at their avatars, and turns the microphone on with a button.
// plaza.ts
import { connect, defineSchema, entity } from "@irtio/client";
import { joinVoice } from "@irtio/client/voice";
const Avatar = entity("avatar", { owner: "string", x: "f32", y: "f32" });
const schema = defineSchema({ entities: [Avatar] });
const room = await connect("plaza", { schema });
const voice = joinVoice(room, {
position(player) {
const avatar = [...room.entities.all(Avatar)].find((a) => a.owner === player);
return avatar && { x: avatar.x, y: avatar.y };
},
range: 30,
});
document.querySelector("#talk")?.addEventListener("click", () => {
voice.enableMic().catch((e: Error) => console.error(`microphone: ${e.message}`));
});
See also
VoiceRoomClient.peers, for who the room has this player hear- Proximity voice
Runtime availability
| Browsers | |
|---|---|
joinVoice() | 5.0 |