Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions apps/singularity-client/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { MicrophoneService } from './sing/services/microphone.service';

@Component({
selector: 'singularity-root',
Expand All @@ -7,4 +8,13 @@ import { ChangeDetectionStrategy, Component } from '@angular/core';
standalone: false,
changeDetection: ChangeDetectionStrategy.Eager
})
export class AppComponent {}
export class AppComponent implements OnInit {
constructor(private readonly microphoneService: MicrophoneService) {
}

public ngOnInit(): void {
this.microphoneService.requestPermission$().subscribe({
error: (error: unknown) => console.error('Unable to access the microphone', error)
});
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { TestBed } from '@angular/core/testing';
import { firstValueFrom } from 'rxjs';

import { MicrophoneService } from './microphone.service';

Expand All @@ -13,4 +14,38 @@ describe('MicrophoneService', () => {
it('should be created', () => {
expect(service).toBeTruthy();
});

it('requests microphone access and stops its tracks after permission is granted', async () => {
let requestedConstraints: MediaStreamConstraints | undefined;
let trackStopped = false;
const mediaDevicesDescriptor = Object.getOwnPropertyDescriptor(navigator, 'mediaDevices');
Object.defineProperty(navigator, 'mediaDevices', {
configurable: true,
value: {
getUserMedia: (constraints: MediaStreamConstraints) => {
requestedConstraints = constraints;
return Promise.resolve({
getTracks: () => [{
stop: () => {
trackStopped = true;
}
}]
} as unknown as MediaStream);
}
}
});

try {
await firstValueFrom(service.requestPermission$());

expect(requestedConstraints).toEqual({ audio: true });
expect(trackStopped).toBe(true);
} finally {
if (mediaDevicesDescriptor) {
Object.defineProperty(navigator, 'mediaDevices', mediaDevicesDescriptor);
} else {
Reflect.deleteProperty(navigator, 'mediaDevices');
}
}
});
});
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Injectable } from '@angular/core';
import { asyncScheduler, finalize, from, map, Observable, scheduled, switchMap, take, timer } from 'rxjs';
import { asyncScheduler, defer, finalize, from, map, Observable, scheduled, switchMap, take, tap, timer } from 'rxjs';

@Injectable({providedIn: 'root'})
export class MicrophoneService {

private selectedMicrophones: string[] = [];
private audioContext = new AudioContext({ latencyHint: 0 });
private audioContext?: AudioContext;

public isAnyMicrophoneSelected(): boolean {
return this.selectedMicrophones.length > 0;
Expand All @@ -27,6 +27,14 @@ export class MicrophoneService {
)
}

public requestPermission$(): Observable<void> {
return defer(() => from(navigator.mediaDevices.getUserMedia({ audio: true })))
.pipe(
tap((stream: MediaStream) => stream.getTracks().forEach(track => track.stop())),
map(() => undefined)
);
}

public getDeviceStream$(deviceId: string): Observable<MediaStream> {
// We are using swicthMap and scheduled here, so that this observable does not become a hot observable.
return scheduled([1], asyncScheduler)
Expand All @@ -47,10 +55,10 @@ export class MicrophoneService {
return this.getDeviceStream$(deviceId)
.pipe(
switchMap((stream: MediaStream) => {
const analyser = this.audioContext.createAnalyser();
const analyser = this.getAudioContext().createAnalyser();
analyser.fftSize = 512;
analyser.smoothingTimeConstant = 0.1;
const sourceNode = this.audioContext.createMediaStreamSource(stream);
const sourceNode = this.getAudioContext().createMediaStreamSource(stream);
sourceNode.connect(analyser);

return timer(0, 100).pipe(
Expand All @@ -72,4 +80,9 @@ export class MicrophoneService {
})
);
}

private getAudioContext(): AudioContext {
this.audioContext ??= new AudioContext({ latencyHint: 0 });
return this.audioContext;
}
}