Skip to content

Instantly share code, notes, and snippets.

@kwindla
Created February 1, 2021 04:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwindla/5b55e4eef09a7352452608e5859f903f to your computer and use it in GitHub Desktop.
Save kwindla/5b55e4eef09a7352452608e5859f903f to your computer and use it in GitHub Desktop.
audio-only WebRTC calls with the Daily API
<html>
<head>
<title>audio-only with WebRTC and the Daily API</title>
<script src="https://unpkg.com/@daily-co/daily-js"></script>
</head>
<body onload="main()">
<!--
very simple controls just to show basic functionality: join, leave, mute/unmute.
in this sample code we don't update the UI state at all, or do any error
checking.
for reference docs, see https://docs.daily.co/reference#using-the-dailyco-front-end-library
for a full sample app, see https://www.daily.co/blog/building-a-custom-video-chat-app-with-react/
-->
<div id="local-controls">
<button id="join" onclick="joinRoom()">join room</button>
<hr />
<button id="leave" onclick="leaveRoom()">leave room</button>
<hr />
<button id="toggle-mic" onclick="call.setLocalAudio(!call.localAudio())">
toggle mic state
</button>
<hr />
</div>
<script>
async function main() {
// CHANGE THIS TO A ROOM WITHIN YOUR DAILY ACCOUNT
const ROOM_URL = "https:// A ROOM URL HERE";
window.call = DailyIframe.createCallObject({
url: ROOM_URL,
// audioSource can be true, false, or a MediaStreamTrack object
audioSource: true,
videoSource: false,
dailyConfig: {
experimentalChromeVideoMuteLightOff: true,
},
});
call.on("joined-meeting", () => console.log("[JOINED MEETING]"));
call.on("error", (e) => console.error(e));
call.on("track-started", playTrack);
call.on("track-stopped", destroyTrack);
}
async function joinRoom() {
await call.join();
}
async function leaveRoom() {
await call.leave();
}
// ----
function playTrack(evt) {
console.log(
"[TRACK STARTED]",
evt.participant && evt.participant.session_id
);
// sanity check to make sure this is an audio track
if (!(evt.track && evt.track.kind === "audio")) {
console.error("!!! playTrack called without an audio track !!!", evt);
return;
}
// don't play the local audio track (echo!)
if (evt.participant.local) {
return;
}
let audioEl = document.createElement("audio");
document.body.appendChild(audioEl);
audioEl.srcObject = new MediaStream([evt.track]);
audioEl.play();
}
function destroyTrack(evt) {
console.log(
"[TRACK STOPPED]",
(evt.participant && evt.participant.session_id) || "[left meeting]"
);
let els = Array.from(document.getElementsByTagName("video")).concat(
Array.from(document.getElementsByTagName("audio"))
);
for (let el of els) {
if (el.srcObject && el.srcObject.getTracks()[0] === evt.track) {
el.remove();
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment