Skip to content

Play a sound for a new message ​

A short sound tells the person that the world answered while they were looking elsewhere. On every change of the world, look at the newest message and play the sound when that message is new and comes from someone else. Browsers allow audio only after a click in the page. For this reason the view creates its AudioContext on the first click of the person and plays sounds from then on. Press Say hello to hear it.

jsx
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';

// The fake café answers every message.
const cafe = {
	name: 'Café',
	onMessage: (message) => `You said: ${message.text}`,
};

// Plays a short "ding" made by the browser itself, with no sound file to load.
function playDing(audio) {
	const tone = audio.createOscillator();
	const volume = audio.createGain();
	tone.frequency.value = 880;
	volume.gain.value = 0.2;
	tone.connect(volume).connect(audio.destination);
	tone.start();
	tone.stop(audio.currentTime + 0.15);
}

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: cafe } });
	// The player is made at the first click, because browsers play sound only after the person has clicked in the page.
	const audio = useRef(null);
	// The newest message already seen, undefined until the first drawing.
	const newestId = useRef(undefined);
	const [played, setPlayed] = useState(0);

	const newest = world ? world.messages.at(-1) : undefined;
	useEffect(() => {
		if (!world) return;
		// Play a sound for a new message from the world (not from the person, not one there at the start).
		const isNew = newest && newestId.current !== undefined && newest.id !== newestId.current && !newest.fromMe;
		if (isNew && audio.current) {
			playDing(audio.current);
			setPlayed((count) => count + 1);
		}
		newestId.current = newest ? newest.id : null;
	}, [world, newest]);

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	function sayHello() {
		if (!audio.current) audio.current = new AudioContext();
		world.send('hello');
	}

	const last = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<>
			<button onClick={sayHello}>Say hello</button>
			<p>{last ? last.text : 'No answer yet.'}</p>
			<p>Sounds played: {played}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The fake café answers every message.
const cafe = {
	name: 'Café',
	onMessage: (message) => `You said: ${message.text}`,
};

// Plays a short "ding" made by the browser itself, with no sound file to load.
function playDing(audio) {
	const tone = audio.createOscillator();
	const volume = audio.createGain();
	tone.frequency.value = 880;
	volume.gain.value = 0.2;
	tone.connect(volume).connect(audio.destination);
	tone.start();
	tone.stop(audio.currentTime + 0.15);
}

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: cafe } });

// The player is made at the first click, because browsers play sound only after the person has clicked in the page.
let audio = null;
let played = 0;

const button = document.createElement('button');
button.textContent = 'Say hello';
button.onclick = () => {
	if (!audio) audio = new AudioContext();
	world.send('hello');
};
const answer = document.createElement('p');
const count = document.createElement('p');
document.body.append(button, answer, count);

// The newest message already seen, undefined until the first drawing.
let newestId;

// Called at once, then after every change of the world.
world.subscribe((node) => {
	const newest = node.messages.at(-1);
	// Play a sound for a new message from the world (not from the person, not one there at the start).
	const isNew = newest && newestId !== undefined && newest.id !== newestId && !newest.fromMe;
	if (isNew && audio) {
		playDing(audio);
		played += 1;
	}
	newestId = newest ? newest.id : null;

	const last = node.messages.filter((message) => !message.fromMe).at(-1);
	answer.textContent = last ? last.text : 'No answer yet.';
	count.textContent = `Sounds played: ${played}`;
});
Live, on a fake world
Open

How it works ​

  • subscribe calls its listener on every change of the world and not only for new messages. The view detects a new message by comparing the id of the newest one with the last one it saw and skips both the messages of the person (fromMe) and those already present when the view opened.
  • The browser synthesizes the sound with an AudioContext (a tone of 880 Hz for 0.15 seconds) with no file to load. To play a file of your own, call new Audio('/sounds/ding.mp3').play().
  • Always show the new message on screen too for people who do not hear the sound or whose phone is on silent (Accessibility).

See also ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.