MCPcopy Create free account
hub / github.com/Roy3838/Observer / startSystemAudioCapture

Function startSystemAudioCapture

app/src/utils/systemAudioCapture.ts:11–58  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

9 * @returns {Promise<MediaStream | null>} A MediaStream containing only the system audio track, or null on failure.
10 */
11export async function startSystemAudioCapture(): Promise<MediaStream | null> {
12 // If we already have an active stream, return it
13 if (activeStream) {
14 return activeStream;
15 }
16
17 try {
18 console.log('Requesting system audio capture...');
19 // We must request video to get the audio prompt in most browsers.
20 const displayStream = await navigator.mediaDevices.getDisplayMedia({
21 video: true,
22 audio: {
23 // These constraints are ideal for Whisper
24 sampleRate: 16000,
25 channelCount: 1,
26 },
27 });
28
29 const audioTrack = displayStream.getAudioTracks()[0];
30 if (!audioTrack) {
31 // User likely didn't check the "Share audio" box.
32 // We should stop the video track as it's not needed.
33 displayStream.getVideoTracks().forEach(track => track.stop());
34 throw new Error("Audio track not shared. Please ensure you check 'Share tab audio' or 'Share system audio'.");
35 }
36
37 // We don't need the video, so we can stop its track immediately.
38 displayStream.getVideoTracks().forEach(track => track.stop());
39
40 // Create a new stream containing only the audio track.
41 const audioStream = new MediaStream([audioTrack]);
42
43 // Store the stream for later use and cleanup
44 activeStream = audioStream;
45
46 // When the user stops sharing via the browser UI, clean up our reference.
47 audioTrack.onended = () => {
48 console.log('System audio sharing stopped by user');
49 activeStream = null;
50 };
51
52 return audioStream;
53 } catch (error) {
54 console.error('System audio capture error:', error);
55 // Re-throw to be handled by the caller (e.g., StreamManager)
56 throw error;
57 }
58}
59
60/**
61 * Stops the active system audio capture stream.

Callers

nothing calls this directly

Calls 3

errorMethod · 0.80
logMethod · 0.45
stopMethod · 0.45

Tested by

no test coverage detected