Riproduci un suono per un messaggio nuovo
Un breve suono dice alla persona che il mondo ha risposto mentre guardava altrove. A ogni cambiamento del mondo guarda il messaggio più recente e riproduci il suono quando quel messaggio è nuovo e viene da qualcun altro. La vista crea il suo AudioContext al primo clic della persona perché i browser permettono l'audio solo dopo un clic nella pagina. Da quel clic in poi la vista può riprodurre suoni. Premi Say hello per sentirlo.
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 worldOpen
Come funziona
subscribechiama il suo listener a ogni cambiamento del mondo e non solo per i messaggi nuovi. La vista riconosce un messaggio nuovo confrontando l'iddel più recente con l'ultimo che ha visto e salta sia i messaggi della persona (fromMe) sia quelli già presenti quando la vista si è aperta.- Il browser sintetizza il suono con un
AudioContext(un tono di 880 Hz per 0,15 secondi) senza nessun file da caricare. Per riprodurre un tuo file chiamanew Audio('/sounds/ding.mp3').play(). - Mostra in ogni caso il messaggio nuovo per chi non sente il suono o ha il telefono in silenzioso (Accessibilità).