feat(ui): implement voice interaction and enhanced home page animations
Introduces a comprehensive voice interaction system and upgrades the home page experience with dynamic typing effects and improved layout transitions. Key changes: - Added `MicrophoneService` for managing media stream lifecycle and permissions. - Added `SpeechRecognitionService` for continuous speech-to-text processing. - Added `VoiceOrbService` using Three.js to render an animated audio-reactive orb. - Enhanced `HomePage` with a randomized typing effect for welcome titles and improved state management for message transitions. - Refactored `AiChatInputComponent` to support seamless switching between text composer and voice recording modes. - Improved `SidebarComponent` navigation logic and styling. - Updated global styles and component CSS for better theme consistency and smoother animations.
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
export type MicrophoneErrorCode = 'unsupported' | 'denied' | 'unavailable' | 'unknown';
|
||||
|
||||
export class MicrophoneError extends Error {
|
||||
constructor(readonly code: MicrophoneErrorCode, message?: string) {
|
||||
super(message ?? code);
|
||||
this.name = 'MicrophoneError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the microphone MediaStream. It does nothing except capture:
|
||||
* the orb (audio level) and speech recognition consume it separately.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class MicrophoneService {
|
||||
private stream: MediaStream | null = null;
|
||||
private endedCleanup: (() => void) | null = null;
|
||||
|
||||
/** `mediaDevices` is undefined on non-secure (http) origins other than localhost. */
|
||||
get isSupported(): boolean {
|
||||
return typeof navigator !== 'undefined' && !!navigator.mediaDevices?.getUserMedia;
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests microphone permission and returns the stream.
|
||||
* @param onEnded called if the capture track ends unexpectedly (e.g. device unplugged).
|
||||
*/
|
||||
async request(onEnded?: () => void): Promise<MediaStream> {
|
||||
if (!this.isSupported) {
|
||||
throw new MicrophoneError('unsupported');
|
||||
}
|
||||
|
||||
this.release();
|
||||
|
||||
let stream: MediaStream;
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
} catch (err) {
|
||||
throw this.mapError(err);
|
||||
}
|
||||
|
||||
this.stream = stream;
|
||||
|
||||
const track = stream.getAudioTracks()[0];
|
||||
if (track && onEnded) {
|
||||
const handler = (): void => onEnded();
|
||||
track.addEventListener('ended', handler);
|
||||
this.endedCleanup = () => track.removeEventListener('ended', handler);
|
||||
}
|
||||
|
||||
return stream;
|
||||
}
|
||||
|
||||
/** Stops every track of the given stream (defaults to the current one). */
|
||||
release(stream: MediaStream | null = this.stream): void {
|
||||
if (!stream) return;
|
||||
|
||||
if (stream === this.stream) {
|
||||
this.endedCleanup?.();
|
||||
this.endedCleanup = null;
|
||||
this.stream = null;
|
||||
}
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
}
|
||||
|
||||
private mapError(err: unknown): MicrophoneError {
|
||||
const name = err instanceof DOMException ? err.name : '';
|
||||
switch (name) {
|
||||
case 'NotAllowedError':
|
||||
case 'SecurityError':
|
||||
case 'PermissionDeniedError':
|
||||
return new MicrophoneError('denied');
|
||||
case 'NotFoundError':
|
||||
case 'DevicesNotFoundError':
|
||||
case 'NotReadableError':
|
||||
case 'TrackStartError':
|
||||
case 'OverconstrainedError':
|
||||
return new MicrophoneError('unavailable');
|
||||
default:
|
||||
return new MicrophoneError('unknown');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
import { Injectable, NgZone, inject } from '@angular/core';
|
||||
|
||||
/* Minimal typings: SpeechRecognition is not part of TypeScript's lib.dom. */
|
||||
interface SpeechRecognitionAlternativeLike {
|
||||
transcript: string;
|
||||
}
|
||||
interface SpeechRecognitionResultLike {
|
||||
readonly isFinal: boolean;
|
||||
readonly length: number;
|
||||
[index: number]: SpeechRecognitionAlternativeLike;
|
||||
}
|
||||
interface SpeechRecognitionEventLike {
|
||||
readonly resultIndex: number;
|
||||
readonly results: { readonly length: number; [index: number]: SpeechRecognitionResultLike };
|
||||
}
|
||||
interface SpeechRecognitionErrorEventLike {
|
||||
readonly error: string;
|
||||
}
|
||||
interface SpeechRecognitionLike {
|
||||
lang: string;
|
||||
continuous: boolean;
|
||||
interimResults: boolean;
|
||||
maxAlternatives: number;
|
||||
onresult: ((event: SpeechRecognitionEventLike) => void) | null;
|
||||
onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;
|
||||
onend: (() => void) | null;
|
||||
onspeechend: (() => void) | null;
|
||||
start(): void;
|
||||
stop(): void;
|
||||
abort(): void;
|
||||
}
|
||||
type SpeechRecognitionCtor = new () => SpeechRecognitionLike;
|
||||
|
||||
export const DEFAULT_SPEECH_LANGUAGE = 'fa-IR';
|
||||
|
||||
export type SpeechErrorKind =
|
||||
| 'permission-denied'
|
||||
| 'audio-capture'
|
||||
| 'network'
|
||||
| 'no-speech'
|
||||
| 'language-not-supported'
|
||||
| 'unsupported'
|
||||
| 'unknown';
|
||||
|
||||
export interface SpeechTranscript {
|
||||
/** Confirmed text for the whole session (never contains duplicates). */
|
||||
final: string;
|
||||
/** Text still being recognized; may change or disappear on the next event. */
|
||||
interim: string;
|
||||
}
|
||||
|
||||
export interface SpeechSessionHandlers {
|
||||
onTranscript(transcript: SpeechTranscript): void;
|
||||
onSpeechEnd?(): void;
|
||||
/** Fatal errors only. The session is already over when this is called. */
|
||||
onError(kind: SpeechErrorKind): void;
|
||||
}
|
||||
|
||||
/** Silent restarts allowed (Chrome ends sessions after pauses) before reporting "no speech". */
|
||||
const MAX_SILENT_RESTARTS = 4;
|
||||
const RESTART_DELAY_MS = 250;
|
||||
const STOP_TIMEOUT_MS = 1500;
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class SpeechRecognitionService {
|
||||
private readonly ngZone = inject(NgZone);
|
||||
private readonly ctor: SpeechRecognitionCtor | null = this.resolveCtor();
|
||||
|
||||
private recognition: SpeechRecognitionLike | null = null;
|
||||
private handlers: SpeechSessionHandlers | null = null;
|
||||
private lang = DEFAULT_SPEECH_LANGUAGE;
|
||||
private running = false;
|
||||
|
||||
private finalText = '';
|
||||
private interimText = '';
|
||||
private silentRestarts = 0;
|
||||
|
||||
private restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private stopTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private stopResolver: ((text: string) => void) | null = null;
|
||||
|
||||
get isSupported(): boolean {
|
||||
return this.ctor !== null;
|
||||
}
|
||||
|
||||
/** Final + interim text right now. */
|
||||
currentText(): string {
|
||||
return this.join(this.finalText, this.interimText);
|
||||
}
|
||||
|
||||
/** Starts a continuous session. Returns false if it could not be started. */
|
||||
start(lang: string, handlers: SpeechSessionHandlers): boolean {
|
||||
if (!this.ctor) return false;
|
||||
|
||||
this.abort();
|
||||
|
||||
this.lang = lang || DEFAULT_SPEECH_LANGUAGE;
|
||||
this.handlers = handlers;
|
||||
this.finalText = '';
|
||||
this.interimText = '';
|
||||
this.silentRestarts = 0;
|
||||
this.running = true;
|
||||
|
||||
if (!this.startRecognition()) {
|
||||
this.abort();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops listening and resolves with the confirmed text, including any
|
||||
* interim text the engine had not finalized yet.
|
||||
*/
|
||||
stop(): Promise<string> {
|
||||
this.clearRestartTimer();
|
||||
this.running = false;
|
||||
|
||||
const recognition = this.recognition;
|
||||
if (!recognition) {
|
||||
return Promise.resolve(this.promoteInterim());
|
||||
}
|
||||
|
||||
return new Promise<string>((resolve) => {
|
||||
this.stopResolver = resolve;
|
||||
this.stopTimer = setTimeout(() => this.resolveStop(true), STOP_TIMEOUT_MS);
|
||||
try {
|
||||
recognition.stop(); // late final results still arrive via onresult, then onend
|
||||
} catch {
|
||||
this.resolveStop(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Immediately terminates the session and discards callbacks. */
|
||||
abort(): void {
|
||||
this.running = false;
|
||||
this.clearRestartTimer();
|
||||
if (this.stopTimer) {
|
||||
clearTimeout(this.stopTimer);
|
||||
this.stopTimer = null;
|
||||
}
|
||||
|
||||
const resolver = this.stopResolver;
|
||||
this.stopResolver = null;
|
||||
|
||||
this.detachRecognition(true);
|
||||
this.handlers = null;
|
||||
resolver?.(this.promoteInterim());
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.abort();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private startRecognition(): boolean {
|
||||
if (!this.ctor) return false;
|
||||
|
||||
const recognition = new this.ctor();
|
||||
recognition.lang = this.lang;
|
||||
recognition.continuous = true;
|
||||
recognition.interimResults = true;
|
||||
recognition.maxAlternatives = 1;
|
||||
|
||||
recognition.onresult = (event) => this.handleResult(event);
|
||||
recognition.onerror = (event) => this.handleError(event);
|
||||
recognition.onspeechend = () => this.emit((h) => h.onSpeechEnd?.());
|
||||
recognition.onend = () => this.handleEnd();
|
||||
|
||||
this.recognition = recognition;
|
||||
try {
|
||||
recognition.start();
|
||||
return true;
|
||||
} catch {
|
||||
this.recognition = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private handleResult(event: SpeechRecognitionEventLike): void {
|
||||
// Entries before resultIndex were delivered (and finalized) in earlier events,
|
||||
// so only entries from resultIndex onward are processed: no duplicated words.
|
||||
let interim = '';
|
||||
for (let i = event.resultIndex; i < event.results.length; i++) {
|
||||
const result = event.results[i];
|
||||
const text = (result[0]?.transcript ?? '').trim();
|
||||
if (!text) continue;
|
||||
|
||||
if (result.isFinal) {
|
||||
this.finalText = this.join(this.finalText, text);
|
||||
} else {
|
||||
interim = this.join(interim, text);
|
||||
}
|
||||
}
|
||||
|
||||
this.interimText = interim;
|
||||
this.silentRestarts = 0;
|
||||
this.emitTranscript();
|
||||
}
|
||||
|
||||
private handleError(event: SpeechRecognitionErrorEventLike): void {
|
||||
switch (event.error) {
|
||||
case 'no-speech': // not fatal: onend decides whether to restart
|
||||
case 'aborted':
|
||||
return;
|
||||
case 'not-allowed':
|
||||
case 'service-not-allowed':
|
||||
this.fail('permission-denied');
|
||||
return;
|
||||
case 'audio-capture':
|
||||
this.fail('audio-capture');
|
||||
return;
|
||||
case 'network':
|
||||
this.fail('network');
|
||||
return;
|
||||
case 'language-not-supported':
|
||||
this.fail('language-not-supported');
|
||||
return;
|
||||
default:
|
||||
this.fail('unknown');
|
||||
}
|
||||
}
|
||||
|
||||
private handleEnd(): void {
|
||||
if (this.stopResolver) {
|
||||
this.resolveStop(false);
|
||||
return;
|
||||
}
|
||||
if (!this.running) return;
|
||||
|
||||
// The engine ended on its own (pause, timeout, ...): keep what we have and restart.
|
||||
this.detachRecognition(false);
|
||||
this.promoteInterim();
|
||||
this.emitTranscript();
|
||||
|
||||
this.silentRestarts++;
|
||||
if (this.silentRestarts > MAX_SILENT_RESTARTS) {
|
||||
this.fail('no-speech');
|
||||
return;
|
||||
}
|
||||
|
||||
this.restartTimer = setTimeout(() => {
|
||||
this.restartTimer = null;
|
||||
if (this.running && !this.startRecognition()) {
|
||||
this.fail('unknown');
|
||||
}
|
||||
}, RESTART_DELAY_MS);
|
||||
}
|
||||
|
||||
private fail(kind: SpeechErrorKind): void {
|
||||
const handlers = this.handlers;
|
||||
this.running = false;
|
||||
this.clearRestartTimer();
|
||||
this.detachRecognition(true);
|
||||
this.emitWith(handlers, (h) => h.onError(kind));
|
||||
}
|
||||
|
||||
private resolveStop(abortEngine: boolean): void {
|
||||
if (this.stopTimer) {
|
||||
clearTimeout(this.stopTimer);
|
||||
this.stopTimer = null;
|
||||
}
|
||||
const resolver = this.stopResolver;
|
||||
this.stopResolver = null;
|
||||
|
||||
const text = this.promoteInterim();
|
||||
this.detachRecognition(abortEngine);
|
||||
resolver?.(text);
|
||||
}
|
||||
|
||||
/** Commits interim text to final text (used when a session ends mid-phrase). */
|
||||
private promoteInterim(): string {
|
||||
if (this.interimText) {
|
||||
this.finalText = this.join(this.finalText, this.interimText);
|
||||
this.interimText = '';
|
||||
}
|
||||
return this.finalText;
|
||||
}
|
||||
|
||||
private detachRecognition(abortEngine: boolean): void {
|
||||
const recognition = this.recognition;
|
||||
this.recognition = null;
|
||||
if (!recognition) return;
|
||||
|
||||
recognition.onresult = null;
|
||||
recognition.onerror = null;
|
||||
recognition.onend = null;
|
||||
recognition.onspeechend = null;
|
||||
if (abortEngine) {
|
||||
try {
|
||||
recognition.abort();
|
||||
} catch {
|
||||
/* already stopped */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private clearRestartTimer(): void {
|
||||
if (this.restartTimer) {
|
||||
clearTimeout(this.restartTimer);
|
||||
this.restartTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private emitTranscript(): void {
|
||||
const transcript: SpeechTranscript = { final: this.finalText, interim: this.interimText };
|
||||
this.emit((h) => h.onTranscript(transcript));
|
||||
}
|
||||
|
||||
private emit(fn: (handlers: SpeechSessionHandlers) => void): void {
|
||||
this.emitWith(this.handlers, fn);
|
||||
}
|
||||
|
||||
/** Speech events may fire outside Angular's zone; always hand results back inside it. */
|
||||
private emitWith(
|
||||
handlers: SpeechSessionHandlers | null,
|
||||
fn: (handlers: SpeechSessionHandlers) => void,
|
||||
): void {
|
||||
if (!handlers) return;
|
||||
this.ngZone.run(() => fn(handlers));
|
||||
}
|
||||
|
||||
private join(a: string, b: string): string {
|
||||
return a && b ? `${a} ${b}` : a || b;
|
||||
}
|
||||
|
||||
private resolveCtor(): SpeechRecognitionCtor | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
const w = window as unknown as {
|
||||
SpeechRecognition?: SpeechRecognitionCtor;
|
||||
webkitSpeechRecognition?: SpeechRecognitionCtor;
|
||||
};
|
||||
return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
|
||||
}
|
||||
}
|
||||
@@ -1,57 +1,77 @@
|
||||
import { Injectable, NgZone, inject } from '@angular/core';
|
||||
import * as THREE from 'three';
|
||||
import { mergeVertices } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
|
||||
|
||||
/** Icosphere subdivision. 20 → ~4.4k shared vertices: smooth and cheap to deform every frame. */
|
||||
const ORB_DETAIL = 20;
|
||||
const FALLBACK_SIZE = 260;
|
||||
|
||||
/**
|
||||
* Renders the animated voice orb and derives an audio level from a MediaStream.
|
||||
* It never requests the microphone itself: MicrophoneService owns the stream,
|
||||
* this service only analyses it (attachStream / detachAudio).
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class VoiceOrbService {
|
||||
private readonly ngZone = inject(NgZone);
|
||||
private readonly reducedMotion =
|
||||
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
private scene: THREE.Scene | null = null;
|
||||
private camera: THREE.PerspectiveCamera | null = null;
|
||||
private renderer: THREE.WebGLRenderer | null = null;
|
||||
private orb: THREE.Mesh | null = null;
|
||||
private orbGeometry: THREE.IcosahedronGeometry | null = null;
|
||||
private orbGeometry: THREE.BufferGeometry | null = null;
|
||||
private glowShell: THREE.Mesh | null = null;
|
||||
private originalPositions: Float32Array | null = null;
|
||||
private resizeObserver: ResizeObserver | null = null;
|
||||
private animationId: number | null = null;
|
||||
|
||||
private audioContext: AudioContext | null = null;
|
||||
private analyser: AnalyserNode | null = null;
|
||||
private mediaStream: MediaStream | null = null;
|
||||
private audioDataArray: Uint8Array | null = null;
|
||||
private isListening = false;
|
||||
private readonly reducedMotion: boolean;
|
||||
private sourceNode: MediaStreamAudioSourceNode | null = null;
|
||||
private audioData: Uint8Array<ArrayBuffer> | null = null;
|
||||
private smoothedLevel = 0;
|
||||
|
||||
constructor(private readonly ngZone: NgZone) {
|
||||
this.reducedMotion = typeof window !== 'undefined'
|
||||
&& window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
}
|
||||
|
||||
init(container: HTMLElement): void {
|
||||
if (this.scene) {
|
||||
if (this.renderer && this.renderer.domElement.parentNode !== container) {
|
||||
/**
|
||||
* Creates the scene once and reuses it on later calls (re-attaching the canvas if needed).
|
||||
* Returns false if WebGL is unavailable so the caller can show a fallback.
|
||||
*/
|
||||
init(container: HTMLElement): boolean {
|
||||
if (this.scene && this.renderer) {
|
||||
if (this.renderer.domElement.parentNode !== container) {
|
||||
container.appendChild(this.renderer.domElement);
|
||||
}
|
||||
this.resize(container);
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
const width = container.clientWidth || 280;
|
||||
const height = container.clientHeight || 280;
|
||||
const width = container.clientWidth || FALLBACK_SIZE;
|
||||
const height = container.clientHeight || FALLBACK_SIZE;
|
||||
|
||||
let renderer: THREE.WebGLRenderer;
|
||||
try {
|
||||
renderer = new THREE.WebGLRenderer({
|
||||
antialias: true,
|
||||
alpha: true,
|
||||
powerPreference: 'high-performance',
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('VoiceOrbService: WebGL is not available.', err);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.renderer = renderer;
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
renderer.setSize(width, height, false); // CSS controls the displayed size
|
||||
renderer.setClearColor(0x000000, 0);
|
||||
container.appendChild(renderer.domElement);
|
||||
|
||||
this.scene = new THREE.Scene();
|
||||
|
||||
this.camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100);
|
||||
this.camera.position.z = 4;
|
||||
|
||||
this.renderer = new THREE.WebGLRenderer({
|
||||
antialias: true,
|
||||
alpha: true,
|
||||
powerPreference: 'high-performance',
|
||||
});
|
||||
this.renderer.setSize(width, height);
|
||||
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
this.renderer.setClearColor(0x000000, 0);
|
||||
container.appendChild(this.renderer.domElement);
|
||||
|
||||
const ambientLight = new THREE.AmbientLight(0x404060, 2);
|
||||
this.scene.add(ambientLight);
|
||||
this.scene.add(new THREE.AmbientLight(0x404060, 2));
|
||||
|
||||
const pointLight1 = new THREE.PointLight(0x3b82f6, 12, 10);
|
||||
pointLight1.position.set(0, 0, 3);
|
||||
@@ -65,7 +85,16 @@ export class VoiceOrbService {
|
||||
pointLight3.position.set(2, -1, 2);
|
||||
this.scene.add(pointLight3);
|
||||
|
||||
this.orbGeometry = new THREE.IcosahedronGeometry(1, 48);
|
||||
// Icosahedron geometry is non-indexed (faceted normals). Dropping normal/uv and
|
||||
// merging vertices gives a shared-vertex mesh, so computeVertexNormals() is smooth.
|
||||
let geometry: THREE.BufferGeometry = new THREE.IcosahedronGeometry(1, ORB_DETAIL);
|
||||
geometry.deleteAttribute('normal');
|
||||
geometry.deleteAttribute('uv');
|
||||
geometry = mergeVertices(geometry, 1e-4);
|
||||
geometry.computeVertexNormals();
|
||||
this.orbGeometry = geometry;
|
||||
this.originalPositions = new Float32Array(geometry.attributes['position'].array);
|
||||
|
||||
const orbMaterial = new THREE.MeshPhysicalMaterial({
|
||||
color: 0x60a5fa,
|
||||
emissive: 0x1e3a5f,
|
||||
@@ -75,12 +104,9 @@ export class VoiceOrbService {
|
||||
clearcoat: 1,
|
||||
clearcoatRoughness: 0.08,
|
||||
});
|
||||
this.orb = new THREE.Mesh(this.orbGeometry, orbMaterial);
|
||||
this.orb = new THREE.Mesh(geometry, orbMaterial);
|
||||
this.scene.add(this.orb);
|
||||
|
||||
this.originalPositions = new Float32Array(this.orbGeometry.attributes['position'].array);
|
||||
|
||||
const glowGeometry = new THREE.IcosahedronGeometry(1.18, 32);
|
||||
const glowMaterial = new THREE.MeshBasicMaterial({
|
||||
color: 0x3b82f6,
|
||||
transparent: true,
|
||||
@@ -89,31 +115,29 @@ export class VoiceOrbService {
|
||||
side: THREE.BackSide,
|
||||
depthWrite: false,
|
||||
});
|
||||
this.glowShell = new THREE.Mesh(glowGeometry, glowMaterial);
|
||||
this.glowShell = new THREE.Mesh(new THREE.IcosahedronGeometry(1.18, 16), glowMaterial);
|
||||
this.scene.add(this.glowShell);
|
||||
|
||||
this.setupResizeObserver(container);
|
||||
this.observeResize(container);
|
||||
this.renderer.render(this.scene, this.camera); // first frame, even before animation starts
|
||||
return true;
|
||||
}
|
||||
|
||||
private setupResizeObserver(container: HTMLElement): void {
|
||||
if (typeof ResizeObserver === 'undefined') return;
|
||||
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const { width, height } = entry.contentRect;
|
||||
if (width > 0 && height > 0 && this.renderer && this.camera) {
|
||||
this.renderer.setSize(width, height);
|
||||
this.camera.aspect = width / height;
|
||||
this.camera.updateProjectionMatrix();
|
||||
}
|
||||
}
|
||||
});
|
||||
observer.observe(container);
|
||||
resize(container: HTMLElement): void {
|
||||
if (!this.renderer || !this.camera) return;
|
||||
const width = container.clientWidth || FALLBACK_SIZE;
|
||||
const height = container.clientHeight || FALLBACK_SIZE;
|
||||
this.renderer.setSize(width, height, false);
|
||||
this.camera.aspect = width / height;
|
||||
this.camera.updateProjectionMatrix();
|
||||
}
|
||||
|
||||
// ---- animation loop -------------------------------------------------------
|
||||
|
||||
startAnimation(): void {
|
||||
if (this.animationId !== null) return;
|
||||
if (this.animationId !== null || !this.renderer) return;
|
||||
|
||||
// The loop runs outside Angular so 60 frames/s never trigger change detection.
|
||||
this.ngZone.runOutsideAngular(() => {
|
||||
const animate = (): void => {
|
||||
this.animationId = requestAnimationFrame(animate);
|
||||
@@ -130,158 +154,69 @@ export class VoiceOrbService {
|
||||
}
|
||||
}
|
||||
|
||||
private renderFrame(): void {
|
||||
if (!this.scene || !this.camera || !this.renderer || !this.orb || !this.orbGeometry) {
|
||||
return;
|
||||
}
|
||||
|
||||
const time = performance.now() * 0.001;
|
||||
const audioLevel = this.getAudioLevel();
|
||||
const speed = this.reducedMotion ? 0.35 : 1;
|
||||
const t = time * speed;
|
||||
|
||||
this.updateOrbGeometry(t, audioLevel);
|
||||
|
||||
if (this.glowShell) {
|
||||
const glowOpacity = 0.05 + audioLevel * 0.18;
|
||||
const glowScale = 1 + Math.sin(t * 1.5) * 0.025 + audioLevel * 0.06;
|
||||
this.glowShell.scale.setScalar(glowScale);
|
||||
if (this.glowShell.material instanceof THREE.MeshBasicMaterial) {
|
||||
this.glowShell.material.opacity = glowOpacity;
|
||||
}
|
||||
}
|
||||
|
||||
const pulse = 1 + Math.sin(t * 2) * 0.018 + audioLevel * 0.07;
|
||||
this.orb.scale.setScalar(pulse);
|
||||
|
||||
this.orb.rotation.y = t * 0.08;
|
||||
this.orb.rotation.x = Math.sin(t * 0.15) * 0.1;
|
||||
|
||||
this.renderer.render(this.scene, this.camera);
|
||||
}
|
||||
|
||||
private updateOrbGeometry(time: number, audioLevel: number): void {
|
||||
if (!this.orbGeometry || !this.originalPositions) return;
|
||||
|
||||
const positions = this.orbGeometry.attributes['position'];
|
||||
const original = this.originalPositions;
|
||||
|
||||
for (let i = 0; i < positions.count; i++) {
|
||||
const ox = original[i * 3];
|
||||
const oy = original[i * 3 + 1];
|
||||
const oz = original[i * 3 + 2];
|
||||
|
||||
const n1 =
|
||||
Math.sin(ox * 3 + time * 1.2) *
|
||||
Math.cos(oy * 3 + time * 0.8) *
|
||||
Math.sin(oz * 3 + time * 1.5) *
|
||||
0.06;
|
||||
|
||||
const n2 =
|
||||
Math.sin(ox * 6 + time * 2.3) *
|
||||
Math.cos(oy * 6 + time * 1.7) *
|
||||
Math.sin(oz * 6 + time * 2.1) *
|
||||
0.02;
|
||||
|
||||
const n3 =
|
||||
Math.cos(ox * 2 + time * 0.6) *
|
||||
Math.sin(oy * 2 + time * 1.1) *
|
||||
0.015;
|
||||
|
||||
const displacement = 1 + n1 + n2 + n3 + audioLevel * 0.12;
|
||||
|
||||
positions.setXYZ(i, ox * displacement, oy * displacement, oz * displacement);
|
||||
}
|
||||
|
||||
positions.needsUpdate = true;
|
||||
this.orbGeometry.computeVertexNormals();
|
||||
}
|
||||
|
||||
resetOrbGeometry(): void {
|
||||
if (!this.orbGeometry || !this.originalPositions) return;
|
||||
const positions = this.orbGeometry.attributes['position'];
|
||||
const original = this.originalPositions;
|
||||
for (let i = 0; i < positions.count; i++) {
|
||||
positions.setXYZ(i, original[i * 3], original[i * 3 + 1], original[i * 3 + 2]);
|
||||
}
|
||||
positions.array.set(this.originalPositions);
|
||||
positions.needsUpdate = true;
|
||||
this.orbGeometry.computeVertexNormals();
|
||||
this.smoothedLevel = 0;
|
||||
}
|
||||
|
||||
resize(container: HTMLElement): void {
|
||||
if (!this.renderer || !this.camera) return;
|
||||
const width = container.clientWidth || 280;
|
||||
const height = container.clientHeight || 280;
|
||||
this.renderer.setSize(width, height);
|
||||
this.camera.aspect = width / height;
|
||||
this.camera.updateProjectionMatrix();
|
||||
}
|
||||
|
||||
async startListening(): Promise<void> {
|
||||
if (this.isListening) return;
|
||||
// ---- audio ----------------------------------------------------------------
|
||||
|
||||
/** Starts analysing the stream. The stream stays owned (and stopped) by the caller. */
|
||||
attachStream(stream: MediaStream): void {
|
||||
this.detachAudio();
|
||||
try {
|
||||
this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
this.audioContext = new AudioContext();
|
||||
const source = this.audioContext.createMediaStreamSource(this.mediaStream);
|
||||
void this.audioContext.resume().catch(() => undefined);
|
||||
this.sourceNode = this.audioContext.createMediaStreamSource(stream);
|
||||
this.analyser = this.audioContext.createAnalyser();
|
||||
this.analyser.fftSize = 256;
|
||||
this.analyser.smoothingTimeConstant = 0.75;
|
||||
source.connect(this.analyser);
|
||||
this.audioDataArray = new Uint8Array(this.analyser.frequencyBinCount);
|
||||
this.isListening = true;
|
||||
this.sourceNode.connect(this.analyser);
|
||||
this.audioData = new Uint8Array(this.analyser.frequencyBinCount);
|
||||
} catch (err) {
|
||||
console.warn('VoiceOrbService: unable to access microphone.', err);
|
||||
this.isListening = false;
|
||||
// The orb keeps animating from time alone.
|
||||
console.warn('VoiceOrbService: audio analysis unavailable.', err);
|
||||
this.detachAudio();
|
||||
}
|
||||
}
|
||||
|
||||
stopListening(): void {
|
||||
if (this.mediaStream) {
|
||||
this.mediaStream.getTracks().forEach((track) => track.stop());
|
||||
this.mediaStream = null;
|
||||
}
|
||||
/** Stops audio-reactive processing (does not stop the MediaStream tracks). */
|
||||
detachAudio(): void {
|
||||
this.sourceNode?.disconnect();
|
||||
this.sourceNode = null;
|
||||
this.analyser = null;
|
||||
this.audioData = null;
|
||||
this.smoothedLevel = 0;
|
||||
if (this.audioContext && this.audioContext.state !== 'closed') {
|
||||
this.audioContext.close().catch(() => {});
|
||||
this.audioContext.close().catch(() => undefined);
|
||||
}
|
||||
this.audioContext = null;
|
||||
this.analyser = null;
|
||||
this.audioDataArray = null;
|
||||
this.isListening = false;
|
||||
}
|
||||
|
||||
private getAudioLevel(): number {
|
||||
if (!this.isListening || !this.analyser || !this.audioDataArray) return 0;
|
||||
this.analyser.getByteFrequencyData(this.audioDataArray as Uint8Array<ArrayBuffer>);
|
||||
let sum = 0;
|
||||
for (let i = 0; i < this.audioDataArray.length; i++) {
|
||||
sum += this.audioDataArray[i];
|
||||
}
|
||||
return Math.min(1, sum / this.audioDataArray.length / 200);
|
||||
}
|
||||
// ---- cleanup --------------------------------------------------------------
|
||||
|
||||
dispose(): void {
|
||||
this.stopAnimation();
|
||||
this.stopListening();
|
||||
this.detachAudio();
|
||||
|
||||
this.resizeObserver?.disconnect();
|
||||
this.resizeObserver = null;
|
||||
|
||||
[this.orb, this.glowShell].forEach((mesh) => {
|
||||
if (!mesh) return;
|
||||
mesh.geometry.dispose();
|
||||
(Array.isArray(mesh.material) ? mesh.material : [mesh.material]).forEach((m) => m.dispose());
|
||||
});
|
||||
this.scene?.clear();
|
||||
|
||||
if (this.orbGeometry) this.orbGeometry.dispose();
|
||||
if (this.orb && this.orb.material instanceof THREE.Material) {
|
||||
this.orb.material.dispose();
|
||||
}
|
||||
if (this.glowShell) {
|
||||
if (this.glowShell.material instanceof THREE.Material) {
|
||||
this.glowShell.material.dispose();
|
||||
}
|
||||
if (this.glowShell.geometry) {
|
||||
this.glowShell.geometry.dispose();
|
||||
}
|
||||
}
|
||||
if (this.renderer) {
|
||||
this.renderer.dispose();
|
||||
const canvas = this.renderer.domElement;
|
||||
if (canvas.parentNode) {
|
||||
canvas.parentNode.removeChild(canvas);
|
||||
}
|
||||
this.renderer.dispose();
|
||||
canvas.parentNode?.removeChild(canvas);
|
||||
}
|
||||
|
||||
this.scene = null;
|
||||
@@ -292,4 +227,95 @@ export class VoiceOrbService {
|
||||
this.glowShell = null;
|
||||
this.originalPositions = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- internals ------------------------------------------------------------
|
||||
|
||||
private observeResize(container: HTMLElement): void {
|
||||
if (typeof ResizeObserver === 'undefined') return;
|
||||
this.resizeObserver?.disconnect();
|
||||
this.resizeObserver = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const { width, height } = entry.contentRect;
|
||||
if (width > 0 && height > 0 && this.renderer && this.camera) {
|
||||
this.renderer.setSize(width, height, false);
|
||||
this.camera.aspect = width / height;
|
||||
this.camera.updateProjectionMatrix();
|
||||
}
|
||||
}
|
||||
});
|
||||
this.resizeObserver.observe(container);
|
||||
}
|
||||
|
||||
private renderFrame(): void {
|
||||
if (!this.scene || !this.camera || !this.renderer || !this.orb) return;
|
||||
|
||||
const speed = this.reducedMotion ? 0.35 : 1;
|
||||
const t = performance.now() * 0.001 * speed;
|
||||
const level = this.updateAudioLevel();
|
||||
|
||||
this.updateOrbGeometry(t, level);
|
||||
|
||||
if (this.glowShell) {
|
||||
this.glowShell.scale.setScalar(1 + Math.sin(t * 1.5) * 0.025 + level * 0.06);
|
||||
if (this.glowShell.material instanceof THREE.MeshBasicMaterial) {
|
||||
this.glowShell.material.opacity = 0.05 + level * 0.18;
|
||||
}
|
||||
}
|
||||
|
||||
this.orb.scale.setScalar(1 + Math.sin(t * 2) * 0.018 + level * 0.07);
|
||||
this.orb.rotation.y = t * 0.08;
|
||||
this.orb.rotation.x = Math.sin(t * 0.15) * 0.1;
|
||||
|
||||
this.renderer.render(this.scene, this.camera);
|
||||
}
|
||||
|
||||
private updateOrbGeometry(time: number, level: number): void {
|
||||
if (!this.orbGeometry || !this.originalPositions) return;
|
||||
|
||||
const positions = this.orbGeometry.attributes['position'];
|
||||
const original = this.originalPositions;
|
||||
const amplitude = (this.reducedMotion ? 0.4 : 1) * (1 + level * 2.2);
|
||||
const swell = level * 0.08;
|
||||
|
||||
for (let i = 0; i < positions.count; i++) {
|
||||
const ox = original[i * 3];
|
||||
const oy = original[i * 3 + 1];
|
||||
const oz = original[i * 3 + 2];
|
||||
|
||||
const n1 =
|
||||
Math.sin(ox * 3 + time * 1.2) * Math.cos(oy * 3 + time * 0.8) * Math.sin(oz * 3 + time * 1.5) * 0.06;
|
||||
const n2 =
|
||||
Math.sin(ox * 6 + time * 2.3) * Math.cos(oy * 6 + time * 1.7) * Math.sin(oz * 6 + time * 2.1) * 0.02;
|
||||
const n3 = Math.cos(ox * 2 + time * 0.6) * Math.sin(oy * 2 + time * 1.1) * 0.015;
|
||||
|
||||
const k = 1 + (n1 + n2 + n3) * amplitude + swell;
|
||||
positions.setXYZ(i, ox * k, oy * k, oz * k);
|
||||
}
|
||||
|
||||
positions.needsUpdate = true;
|
||||
this.orbGeometry.computeVertexNormals();
|
||||
}
|
||||
|
||||
/** Fast attack, slow release: loud sounds are visible immediately but never jitter. */
|
||||
private updateAudioLevel(): number {
|
||||
const target = this.readAudioLevel();
|
||||
const smoothing = target > this.smoothedLevel ? 0.35 : 0.08;
|
||||
this.smoothedLevel += (target - this.smoothedLevel) * smoothing;
|
||||
return this.smoothedLevel;
|
||||
}
|
||||
|
||||
private readAudioLevel(): number {
|
||||
if (!this.analyser || !this.audioData) return 0;
|
||||
|
||||
this.analyser.getByteFrequencyData(this.audioData);
|
||||
|
||||
// Voice band only (roughly 200 Hz – 9 kHz at 48 kHz sample rate).
|
||||
const end = Math.min(48, this.audioData.length);
|
||||
let sum = 0;
|
||||
for (let i = 1; i < end; i++) sum += this.audioData[i];
|
||||
const average = sum / (end - 1);
|
||||
|
||||
const gain = this.reducedMotion ? 0.5 : 1;
|
||||
return Math.min(1, Math.max(0, (average - 8) / 110)) * gain;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user