Skip to content

Commit 5c88616

Browse files
committed
docs: share a screen with the microphone and system audio
Adds ScreenShareAudioExample, which sends a screen, the microphone and the system output from one runtime over one peer, and documents sending a SystemAudioSource beside the microphone in the desktop capture, system audio, client API and examples guides.
1 parent 986a9bf commit 5c88616

6 files changed

Lines changed: 265 additions & 5 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ The library provides a comprehensive set of Java classes that map to the WebRTC
2525

2626
- **[Cameras and microphones](https://jrtc.dev/guide/media/media-devices)** - Capture from any local device
2727
- **[Screen sharing](https://jrtc.dev/guide/video/desktop-capture)** - Share the full desktop or single application windows
28+
- **[System audio](https://jrtc.dev/guide/audio/system-audio-source)** - Send what the system plays beside a shared screen and the microphone
2829
- **[Video processing](https://jrtc.dev/guide/video/camera-capture#changing-frames-before-they-are-sent)** - Blur a background, draw an overlay or blank out part of the screen before frames are sent
2930
- **[Video views](https://jrtc.dev/guide/client-api#handlers-on-the-ui-thread)** - Ready-made components that show video in Swing with the `webrtc-java-swing` module, or in JavaFX with the `webrtc-java-javafx` module
3031

‎docs/guide/audio/system-audio-source.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ audioTrack.dispose();
5252
systemAudio.dispose(); // or close(), also supported by try-with-resources
5353
```
5454

55+
With the [Client API](/guide/client-api), pass the source to `audioTrack()`. It
56+
stays yours, so close it only after the track, or the runtime that closes it:
57+
58+
```java
59+
SystemAudioSource systemOutput = new SystemAudioSource();
60+
LocalAudio systemAudio = rtc.media().audioTrack("system-audio", systemOutput);
61+
peer.addTrack(systemAudio, "presentation");
62+
systemOutput.start();
63+
```
64+
5565
Use `try/finally` in application code to release these resources on errors too.
5666
`stop()` and `dispose()` are idempotent. `stop()` keeps the source and its tracks
5767
usable for `start()` again; disposal is permanent. A stop or disposal from a local
@@ -106,7 +116,9 @@ playout is excluded by ScreenCaptureKit; remote audio played in another process
106116
can still be captured.
107117

108118
Run `SystemAudioExample` from `webrtc-examples` for a capture-only example that
109-
counts received PCM frames without playing them back. The opt-in
119+
counts received PCM frames without playing them back, and
120+
[`ScreenShareAudioExample`](/guide/examples#screen-share-with-audio) to send a
121+
screen, the microphone and the system audio over one peer. The opt-in
110122
`SystemAudioSourceIntegrationTest` (`-Dtest.systemAudio=true`) needs audio playing
111123
on the default output and recording permission; lifecycle tests use deterministic
112124
backends without hardware.

‎docs/guide/client-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ Sender audioSender = peer.addTrack(microphone);
476476
| `screen(ScreenOptions)` | A screen or a window, as the [Desktop Video](/guide/video/desktop-capture) guide describes. |
477477
| `customVideo(String)` | Frames you push. |
478478
| `customAudio(String)` | Audio you push, in every mode. |
479-
| `videoTrack(String, VideoTrackSource)`, `audioTrack(String, AudioTrackSource)` | A source of the core API, such as one the [media module](/guide/media/media-files) feeds. The source stays yours. |
479+
| `videoTrack(String, VideoTrackSource)`, `audioTrack(String, AudioTrackSource)` | A source of the core API, such as one the [media module](/guide/media/media-files) feeds, or a [`SystemAudioSource`](/guide/audio/system-audio-source) for the audio the system plays. The source stays yours. |
480480

481481
```java
482482
Devices devices = media.devices();

‎docs/guide/examples.md‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,37 @@ mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.DesktopVideoExample"
8484
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.DesktopVideoExample" -D"exec.args=window"
8585
```
8686

87+
## System Audio
88+
89+
The [`SystemAudioExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/SystemAudioExample.java) captures the audio the system plays on its default output with a [`SystemAudioSource`](/guide/audio/system-audio-source), and counts the frames that reach a sink of its track, without sending or playing anything.
90+
91+
**Key features demonstrated:**
92+
- Capturing the system output as a local audio track
93+
- Reading the captured audio through a sink of the track
94+
- Stopping the capture and checking it for a failure
95+
96+
Play audio in another application while it runs, and press Enter to stop. On macOS, grant screen and audio recording permission when asked.
97+
98+
```bash
99+
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.SystemAudioExample"
100+
```
101+
102+
## Screen Share with Audio
103+
104+
The [`ScreenShareAudioExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/ScreenShareAudioExample.java) shares a screen together with the microphone and the system audio, from one runtime and over one peer, with the [Client API](/guide/client-api).
105+
106+
**Key features demonstrated:**
107+
- Sending a screen, the microphone and the system output as three tracks of one stream
108+
- Sending a `SystemAudioSource` through `audioTrack()`, beside the microphone
109+
- Telling the received audio tracks apart by their IDs
110+
- Counting received audio without playing it back, which the system audio capture would record again
111+
112+
Each audio sender gets the audio of its own track, so the microphone keeps its echo cancellation and the system output is sent as it plays. Play audio in another application and speak into the microphone while it runs, and press Enter to stop.
113+
114+
```bash
115+
mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.ScreenShareAudioExample"
116+
```
117+
87118
## Media File
88119

89120
The [`MediaFileExample`](https://github.com/devopvoid/webrtc-java/blob/master/webrtc-examples/src/main/java/dev/onvoid/webrtc/examples/MediaFileExample.java) demonstrates how to send a media file over a peer connection, in place of a camera and a microphone. See the [Media Files](/guide/media/media-files) guide for the API it uses.

‎docs/guide/video/desktop-capture.md‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,29 @@ Desktop capture is particularly useful for screen sharing applications, remote a
193193

194194
## Sharing system audio
195195

196-
Add a separate [`SystemAudioSource`](/guide/audio/system-audio-source) audio track
197-
to share output audio alongside desktop video. Window selection applies only to
198-
video; the audio source captures system output independently.
196+
Add a [`SystemAudioSource`](/guide/audio/system-audio-source) audio track to share
197+
the audio the system plays alongside the desktop video, and the microphone as a
198+
third track if the presenter speaks. All three can come from one factory and go
199+
over one peer connection; put them into one stream so the receiver keeps them in
200+
sync. With the [Client API](/guide/client-api):
201+
202+
```java
203+
LocalVideo screen = rtc.media().screen(ScreenOptions.screen(source).build());
204+
LocalAudio microphone = rtc.media().microphone();
205+
206+
// The source is yours: close it after the runtime, which closes its track.
207+
SystemAudioSource systemOutput = new SystemAudioSource();
208+
LocalAudio systemAudio = rtc.media().audioTrack("system-audio", systemOutput);
209+
210+
peer.addTrack(screen, "presentation");
211+
peer.addTrack(microphone, "presentation");
212+
peer.addTrack(systemAudio, "presentation");
213+
214+
systemOutput.start(); // on a background thread in an application with a UI
215+
```
216+
217+
Window selection applies only to video; the audio source captures the whole
218+
system output. Remote call audio played on the captured output is captured too on
219+
Windows and Linux, so route it to another output. The
220+
[`ScreenShareAudioExample`](/guide/examples#screen-share-with-audio) runs this
221+
end to end.
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package dev.onvoid.webrtc.examples;
18+
19+
import java.time.Duration;
20+
import java.util.List;
21+
import java.util.Map;
22+
import java.util.concurrent.ConcurrentHashMap;
23+
import java.util.concurrent.TimeUnit;
24+
import java.util.concurrent.atomic.AtomicInteger;
25+
import java.util.concurrent.atomic.AtomicLong;
26+
27+
import dev.onvoid.webrtc.client.AudioChunk;
28+
import dev.onvoid.webrtc.client.LocalAudio;
29+
import dev.onvoid.webrtc.client.LocalVideo;
30+
import dev.onvoid.webrtc.client.Peer;
31+
import dev.onvoid.webrtc.client.PeerOptions;
32+
import dev.onvoid.webrtc.client.RemoteAudio;
33+
import dev.onvoid.webrtc.client.ScreenOptions;
34+
import dev.onvoid.webrtc.client.Signaling;
35+
import dev.onvoid.webrtc.client.SignalingPair;
36+
import dev.onvoid.webrtc.client.WebRtc;
37+
import dev.onvoid.webrtc.media.audio.SystemAudioSource;
38+
import dev.onvoid.webrtc.media.video.desktop.DesktopSource;
39+
40+
/**
41+
* Example demonstrating how to share a screen together with the microphone and
42+
* the audio the system plays, from one runtime and over one peer, with the
43+
* client API.
44+
* <p>
45+
* This example shows how to:
46+
* <ul>
47+
* <li>Capture a screen, the microphone and the system output as three tracks</li>
48+
* <li>Send the system output through a {@link SystemAudioSource}, beside the microphone</li>
49+
* <li>Put all three tracks into one stream, so the receiver keeps them in sync</li>
50+
* <li>Tell the received audio tracks apart by their IDs</li>
51+
* <li>Stop the system audio capture and check it for a failure</li>
52+
* </ul>
53+
* <p>
54+
* Each audio sender gets the audio of its own track: the microphone, with echo
55+
* cancellation, noise suppression and gain control, on one, and the system
56+
* output, unprocessed, on the other. Both peers run in this process, so the
57+
* call connects without a server. The viewer does not play what it receives:
58+
* on Windows and Linux the system audio capture would record that playout and
59+
* send it again.
60+
* <p>
61+
* Play audio in another application, speak into the microphone, run the
62+
* example and press Enter to stop. On macOS, grant screen and audio recording
63+
* permission when asked:
64+
* <pre>
65+
* mvn exec:java -D"exec.mainClass=dev.onvoid.webrtc.examples.ScreenShareAudioExample"
66+
* </pre>
67+
*
68+
* @author Alex Andres
69+
*/
70+
public class ScreenShareAudioExample {
71+
72+
/** A 16-bit sample above this is counted as sound rather than silence. */
73+
private static final int AUDIBLE = 300;
74+
75+
76+
public static void main(String[] args) throws Exception {
77+
// AudioMode.DEVICES, the default: the microphone is captured, and pushed
78+
// audio such as the system output can be sent beside it.
79+
WebRtc rtc = WebRtc.create();
80+
SystemAudioSource systemOutput = null;
81+
82+
try {
83+
List<DesktopSource> screens = rtc.media().devices().screens();
84+
85+
if (screens.isEmpty()) {
86+
System.out.println("There is no screen to share");
87+
return;
88+
}
89+
90+
DesktopSource source = screens.get(0);
91+
LocalVideo screen = rtc.media().screen(ScreenOptions.screen(source)
92+
.frameRate(30)
93+
.maxSize(1920, 1080)
94+
.build());
95+
LocalAudio microphone = rtc.media().microphone();
96+
97+
// The source stays the application's: it must outlive its track,
98+
// which the runtime closes.
99+
systemOutput = new SystemAudioSource();
100+
LocalAudio systemAudio = rtc.media().audioTrack("system-audio", systemOutput);
101+
102+
SignalingPair signaling = Signaling.loopback();
103+
104+
Peer sharer = rtc.createPeer(PeerOptions.builder()
105+
.name("sharer")
106+
.signaling(signaling.first())
107+
.build());
108+
Peer viewer = rtc.createPeer(PeerOptions.builder()
109+
.name("viewer")
110+
.polite(true)
111+
.signaling(signaling.second())
112+
.build());
113+
114+
AtomicInteger frames = new AtomicInteger();
115+
Map<String, AtomicLong> audibleChunks = new ConcurrentHashMap<>();
116+
117+
viewer.onTrack(track -> {
118+
if (track.isVideo()) {
119+
track.asVideo().onFrame(frame -> frames.incrementAndGet());
120+
return;
121+
}
122+
123+
String name = track.id().equals(systemAudio.id()) ? "system audio" : "microphone";
124+
AtomicLong audible = audibleChunks.computeIfAbsent(name, key -> new AtomicLong());
125+
RemoteAudio audio = track.asAudio();
126+
127+
// Count the audio instead of playing it, which the system audio
128+
// capture would pick up again.
129+
audio.setVolume(0);
130+
audio.onAudio(chunk -> {
131+
if (isAudible(chunk)) {
132+
audible.incrementAndGet();
133+
}
134+
});
135+
});
136+
137+
// One stream for all three tracks, so the viewer lines them up.
138+
sharer.addTrack(screen, "presentation");
139+
sharer.addTrack(microphone, "presentation");
140+
sharer.addTrack(systemAudio, "presentation");
141+
142+
// Waits for the platform to open the output, and on macOS for the
143+
// permission prompt. An application with a user interface calls it
144+
// on a background thread.
145+
systemOutput.start();
146+
147+
// The main thread may wait; a handler must not.
148+
sharer.whenConnected().get(15, TimeUnit.SECONDS);
149+
150+
System.out.println("Sharing " + source.title + " with the microphone and the system audio");
151+
152+
sharer.onStats(Duration.ofSeconds(5), stats -> {
153+
System.out.printf("Viewer got %d frames, audible 10 ms chunks: %s%n",
154+
frames.get(), audibleChunks);
155+
});
156+
157+
System.out.println("Press Enter to stop sharing...");
158+
System.in.read();
159+
160+
systemOutput.stop();
161+
162+
if (systemOutput.getFailure() != null) {
163+
System.out.println("System audio capture failed: " + systemOutput.getFailure());
164+
}
165+
}
166+
finally {
167+
// Closing the runtime closed the peers and the tracks, so the system
168+
// audio source can go now.
169+
rtc.close();
170+
171+
if (systemOutput != null) {
172+
systemOutput.close();
173+
}
174+
}
175+
176+
System.out.println("Closed");
177+
}
178+
179+
private static boolean isAudible(AudioChunk chunk) {
180+
byte[] samples = chunk.samples();
181+
182+
for (int i = 0; i + 1 < samples.length; i += 2) {
183+
// 16-bit little-endian PCM.
184+
int sample = (short) ((samples[i] & 0xff) | (samples[i + 1] << 8));
185+
186+
if (Math.abs(sample) > AUDIBLE) {
187+
return true;
188+
}
189+
}
190+
191+
return false;
192+
}
193+
}

0 commit comments

Comments
 (0)