Voice Quick Start
Prerequisites
The quick start needs a Voice App Id, the SDK set up as described in Voice Setup, a microphone and headphones.
Audio devices are driven by PortAudio. The example's CMakeLists.txt fetches and builds it, which needs network access when configuring. On Linux, the ALSA development package (libasound2-dev or alsa-lib-devel) has to be installed.
The example builds on the Realtime Core Quick Start Guide. Connecting and joining a room are not explained again.
The snippets in the steps below are excerpts. The Full Example shows where each one goes and defines the helpers they refer to.
Create the Clients
The RealtimeClient is constructed with the Voice App Id:
C++
#include "RealtimeCore/Common/ScopedSubscription.h"
#include "RealtimeCore/Matchmaking/RealtimeClient.h"
#include "RealtimeCore/Voice/VoiceClient.h"
using namespace RealtimeCore::Matchmaking;
using namespace RealtimeCore::Voice;
ClientConstructOptions options;
options.AppId = PHOTON_STR("<your-voice-app-id>");
options.AppVersion = PHOTON_STR("voice-quickstart-1.0");
RealtimeClient client(options);
The VoiceClient is created right after, before entering a room:
C++
VoiceClient voice(client);
It starts its streams when the RealtimeClient joins a room. One created inside a room sends nothing until the next join.
Subscribe to Remote Voices
Incoming streams are reported through OnRemoteVoiceAdded and OnRemoteVoiceRemoved. Both are raised from VoiceClient::Service() on the main thread, and each ScopedSubscription has to stay alive for as long as its handler should run. The handlers of the example add each playable voice to a list and remove it again:
C++
constexpr int SamplingRate = 48000;
constexpr int Channels = 1;
using RemoteVoiceList = std::vector<std::shared_ptr<RemoteVoice>>;
RemoteVoiceList remoteVoices; // main thread only
RealtimeCore::Common::ScopedSubscription addedSub = voice.OnRemoteVoiceAdded.Subscribe(
[&](const std::shared_ptr<RemoteVoice>& remote) {
const RemoteVoiceInfo& info = remote->GetInfo();
if (info.SamplingRate != SamplingRate || info.Channels != Channels)
{
return;
}
remoteVoices.push_back(remote);
publishSnapshot();
});
RealtimeCore::Common::ScopedSubscription removedSub = voice.OnRemoteVoiceRemoved.Subscribe(
[&](const std::shared_ptr<RemoteVoice>& remote) {
const auto it = std::find(remoteVoices.begin(), remoteVoices.end(), remote);
if (it != remoteVoices.end())
{
remoteVoices.erase(it);
publishSnapshot();
}
});
The handlers keep the list of voices to play on the main thread and publish an immutable copy of it for the audio thread. The pattern is covered in Sharing Remote Voices With the Audio Thread.
The example plays only 48 kHz mono, the format every instance of it sends, and ignores streams in any other format. The reason is given in Use One Stream Format.
Enter a Room
Connecting and joining run in one coroutine, pumped until it completes, as in the Realtime Core quick start:
C++
Task<Result<Room>> EnterRoom(RealtimeClient& client)
{
Result<void, ConnectError> connected = co_await client.Connect();
if (connected.IsErr())
{
co_return Result<Room>::Err(connected.GetError());
}
co_return co_await client.JoinRandomOrCreateRoom();
}
template <typename T>
T PumpUntilReady(RealtimeClient& client, Task<T> task)
{
while (!task.IsReady())
{
client.Service();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
return task.Get();
}
Result<Room> room = PumpUntilReady(client, EnterRoom(client));
Create a Local Voice
The local voice uses the same format as the audio device. CreateLocalVoice() returns nullptr when it fails:
C++
LocalVoiceOptions voiceOptions;
voiceOptions.SamplingRate = SamplingRate;
voiceOptions.Channels = Channels;
std::unique_ptr<LocalVoice> localVoice = voice.CreateLocalVoice(voiceOptions);
if (localVoice == nullptr)
{
std::puts("CreateLocalVoice failed");
return 1;
}
Voice detection stays off in this example. With it on, nothing is sent until the detector hears speech, which is easy to mistake for a broken microphone.
Connect the Audio Device
The example opens one PortAudio duplex stream on the default devices, at 48 kHz mono with buffers of 10 ms. A single callback handles both capture and playback:
C++
// 10 ms per device callback.
constexpr unsigned long FramesPerBuffer = 480;
PaStream* stream = nullptr;
Pa_Initialize();
Pa_OpenDefaultStream(&stream, Channels, Channels, paFloat32, SamplingRate, FramesPerBuffer, OnAudio, &audio);
Pa_StartStream(stream);
Capture
The callback passes the captured samples to LocalVoice::PushAudio():
C++
if (input != nullptr)
{
context.Voice->PushAudio(std::span<const float>(static_cast<const float*>(input), sampleCount));
}
PushAudio() accepts any number of samples and cuts them into encoder frames itself.
Playback
The same callback reads each remote voice's PlaybackBuffer into a scratch buffer, adds it to the output and clamps the sum:
C++
std::fill(out.begin(), out.end(), 0.0f);
for (const auto& voice : *voices)
{
voice->GetPlaybackBuffer().Read(scratch);
for (std::size_t i = 0; i < sampleCount; ++i)
{
out[i] += scratch[i];
}
}
for (float& sample : out)
{
sample = std::clamp(sample, -1.0f, 1.0f);
}
Read() always fills the buffer and pads with silence until the voice has buffered enough audio.
Drive the Clients
The main loop services both clients every 10 ms:
C++
while (!QuitRequested)
{
client.Service();
voice.Service();
if (!client.IsInRoom())
{
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
Encoded frames are sent from VoiceClient::Service(), which makes the tick interval part of the latency.
Once per second, the example prints the microphone level, whether the voice is transmitting and the frame counters:
C++
const VoiceStats stats = voice.GetStats();
std::printf("mic %.2f %-8s frames sent %d received %d lost %d\n",
localVoice->GetLevel(), localVoice->IsTransmitting() ? "sending" : "idle",
stats.FramesSent, stats.FramesReceived, stats.FramesLost);
Test With Debug Echo
Started with --echo, the example sets LocalVoiceOptions::DebugEcho, and the server sends the stream back to its sender as well. A single instance is then enough to hear the whole round trip. Headphones keep the speaker out of the microphone.
Shut Down
The audio stream is stopped first, because its callback pushes into the local voice and must not touch it once it is destroyed. Then the local voice is destroyed and the client disconnects:
C++
Pa_StopStream(stream);
Pa_CloseStream(stream);
Pa_Terminate();
localVoice.reset();
PumpUntilReady(client, client.Disconnect());
Full Example
The complete main.cpp:
C++
// RealtimeCore voice quick-start sample: enters a room, sends the microphone to the other
// players in it and plays back everyone else. See README.md.
//
// PortAudio only drives the audio devices. The voice API takes and returns plain float
// samples and works with any audio library.
#include "RealtimeCore/Common/ScopedSubscription.h"
#include "RealtimeCore/Matchmaking/RealtimeClient.h"
#include "RealtimeCore/Voice/VoiceClient.h"
#include <portaudio.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <mutex>
#include <span>
#include <thread>
#include <vector>
using namespace RealtimeCore::Matchmaking;
using namespace RealtimeCore::Voice;
namespace
{
// Every instance sends this format, so remote streams mix into the output without
// resampling. A stream in any other format is not played.
constexpr int SamplingRate = 48000;
constexpr int Channels = 1;
// 10 ms per device callback.
constexpr unsigned long FramesPerBuffer = 480;
// Encoded frames are sent from VoiceClient::Service(), so the tick adds to latency.
constexpr auto Tick = std::chrono::milliseconds(10);
using RemoteVoiceList = std::vector<std::shared_ptr<RemoteVoice>>;
// Shared with the audio callback, which runs on PortAudio's thread.
struct AudioContext
{
LocalVoice* Voice = nullptr;
// The main thread replaces the snapshot whenever a voice comes or goes; a published
// list never changes. The callback copies the pointer under the lock and mixes without it.
std::mutex SnapshotMutex;
std::shared_ptr<const RemoteVoiceList> Snapshot = std::make_shared<const RemoteVoiceList>();
std::vector<float> Scratch = std::vector<float>(FramesPerBuffer * Channels);
};
std::atomic<bool> QuitRequested{false};
int OnAudio(const void* input, void* output, unsigned long frameCount, const PaStreamCallbackTimeInfo* /*timeInfo*/,
PaStreamCallbackFlags /*statusFlags*/, void* userData)
{
auto& context = *static_cast<AudioContext*>(userData);
const std::size_t sampleCount = frameCount * Channels;
// PushAudio() takes any number of samples; the voice cuts them into encoder frames.
if (input != nullptr)
{
context.Voice->PushAudio(std::span<const float>(static_cast<const float*>(input), sampleCount));
}
std::shared_ptr<const RemoteVoiceList> voices;
{
const std::lock_guard<std::mutex> lock(context.SnapshotMutex);
voices = context.Snapshot;
}
const std::span<float> out(static_cast<float*>(output), sampleCount);
const std::span<float> scratch(context.Scratch.data(), sampleCount);
std::fill(out.begin(), out.end(), 0.0f);
for (const auto& voice : *voices)
{
// Always fills scratch, padding with silence while the voice buffers.
voice->GetPlaybackBuffer().Read(scratch);
for (std::size_t i = 0; i < sampleCount; ++i)
{
out[i] += scratch[i];
}
}
for (float& sample : out)
{
sample = std::clamp(sample, -1.0f, 1.0f);
}
return paContinue;
}
bool Succeeded(PaError error, const char* what)
{
if (error != paNoError)
{
std::printf("%s failed: %s\n", what, Pa_GetErrorText(error));
return false;
}
return true;
}
RealtimeCore::Common::StringType ToPhotonString(const char* text)
{
return RealtimeCore::Common::StringType(reinterpret_cast<const char8_t*>(text));
}
const char* AsPrintable(const RealtimeCore::Common::StringType& text)
{
return reinterpret_cast<const char*>(text.c_str());
}
// NOLINTBEGIN(cppcoreguidelines-avoid-reference-coroutine-parameters)
Task<Result<Room>> EnterRoom(RealtimeClient& client)
{
Result<void, ConnectError> connected = co_await client.Connect();
if (connected.IsErr())
{
co_return Result<Room>::Err(connected.GetError());
}
co_return co_await client.JoinRandomOrCreateRoom();
}
// NOLINTEND(cppcoreguidelines-avoid-reference-coroutine-parameters)
template <typename T>
T PumpUntilReady(RealtimeClient& client, Task<T> task)
{
while (!task.IsReady())
{
client.Service();
std::this_thread::sleep_for(Tick);
}
return task.Get();
}
} // namespace
int main(int argc, char** argv)
{
const char* appId = std::getenv("PHOTON_APPID");
bool echo = false;
for (int i = 1; i < argc; ++i)
{
if (std::strcmp(argv[i], "--echo") == 0)
{
echo = true;
}
else
{
appId = argv[i];
}
}
if (appId == nullptr || *appId == '\0')
{
std::fputs("usage: voice_quickstart <photon-app-id> [--echo]\n"
" (or set the PHOTON_APPID environment variable)\n\n"
"Run this twice with the same AppId and talk. --echo plays your own voice\n"
"back through the server, so a single instance is enough to hear it work.\n",
stderr);
return 2;
}
ClientConstructOptions options;
options.AppId = ToPhotonString(appId);
options.AppVersion = PHOTON_STR("voice-quickstart-1.0");
RealtimeClient client(options);
// Create the VoiceClient before entering the room: it starts its streams on the join,
// and one created inside a room sends nothing until the next join.
VoiceClient voice(client);
AudioContext audio;
RemoteVoiceList remoteVoices; // main thread only
auto publishSnapshot = [&audio, &remoteVoices]() {
auto snapshot = std::make_shared<const RemoteVoiceList>(remoteVoices);
const std::lock_guard<std::mutex> lock(audio.SnapshotMutex);
audio.Snapshot = std::move(snapshot);
};
// Both are raised from VoiceClient::Service(), on this thread.
RealtimeCore::Common::ScopedSubscription addedSub = voice.OnRemoteVoiceAdded.Subscribe(
[&client, &remoteVoices, &publishSnapshot](const std::shared_ptr<RemoteVoice>& remote) {
const RemoteVoiceInfo& info = remote->GetInfo();
if (info.SamplingRate != SamplingRate || info.Channels != Channels)
{
std::printf("ignoring voice %d of player %d: %d Hz, %d channel(s)\n",
info.VoiceId, info.PlayerNumber, info.SamplingRate, info.Channels);
return;
}
std::printf("voice %d of player %d started%s\n", info.VoiceId, info.PlayerNumber,
info.PlayerNumber == client.GetLocalPlayer().Number ? " (echo)" : "");
remoteVoices.push_back(remote);
publishSnapshot();
});
RealtimeCore::Common::ScopedSubscription removedSub = voice.OnRemoteVoiceRemoved.Subscribe(
[&remoteVoices, &publishSnapshot](const std::shared_ptr<RemoteVoice>& remote) {
const auto it = std::find(remoteVoices.begin(), remoteVoices.end(), remote);
if (it != remoteVoices.end())
{
std::printf("voice %d of player %d stopped\n", remote->GetInfo().VoiceId, remote->GetInfo().PlayerNumber);
remoteVoices.erase(it);
publishSnapshot();
}
});
Result<Room> room = PumpUntilReady(client, EnterRoom(client));
if (room.IsErr())
{
std::printf("failed to enter a room (%d): %s\n",
static_cast<int>(room.GetError().Code),
AsPrintable(room.GetError().Message));
return 1;
}
std::printf("joined room %s as player %d\n", AsPrintable(room.GetValue().GetName()), client.GetLocalPlayer().Number);
LocalVoiceOptions voiceOptions;
voiceOptions.SamplingRate = SamplingRate;
voiceOptions.Channels = Channels;
voiceOptions.DebugEcho = echo;
// VoiceDetection stays off: with it on, nothing is sent until the detector hears speech.
std::unique_ptr<LocalVoice> localVoice = voice.CreateLocalVoice(voiceOptions);
if (localVoice == nullptr)
{
std::puts("CreateLocalVoice failed");
return 1;
}
audio.Voice = localVoice.get();
if (!Succeeded(Pa_Initialize(), "Pa_Initialize"))
{
return 1;
}
PaStream* stream = nullptr;
if (!Succeeded(Pa_OpenDefaultStream(&stream, Channels, Channels, paFloat32, SamplingRate, FramesPerBuffer, OnAudio, &audio), "Pa_OpenDefaultStream")
|| !Succeeded(Pa_StartStream(stream), "Pa_StartStream"))
{
Pa_Terminate();
return 1;
}
std::puts("talking -- press Enter to quit");
std::thread([]() {
std::getchar();
QuitRequested = true;
}).detach();
auto lastStatus = std::chrono::steady_clock::now();
while (!QuitRequested)
{
client.Service();
voice.Service();
if (!client.IsInRoom())
{
std::puts("no longer in a room");
break;
}
const auto now = std::chrono::steady_clock::now();
if (now - lastStatus >= std::chrono::seconds(1))
{
const VoiceStats stats = voice.GetStats();
std::printf("mic %.2f %-8s remote voices %zu frames sent %d received %d lost %d\n",
localVoice->GetLevel(), localVoice->IsTransmitting() ? "sending" : "idle",
remoteVoices.size(), stats.FramesSent, stats.FramesReceived, stats.FramesLost);
lastStatus = now;
}
std::this_thread::sleep_for(Tick);
}
// Stop the callback before destroying what it uses, and the LocalVoice before the
// VoiceClient that owns its stream.
Pa_StopStream(stream);
Pa_CloseStream(stream);
Pa_Terminate();
localVoice.reset();
PumpUntilReady(client, client.Disconnect());
return 0;
}
The complete CMakeLists.txt finds the SDK package, checks that it carries Voice, fetches PortAudio v19.7.0 and links both:
cmake
# RealtimeCore voice quick-start sample. Consumes an installed RealtimeCore package like
# ../QuickStart and adds RealtimeCore::Voice and PortAudio.
cmake_minimum_required(VERSION 3.20)
# C for PortAudio, which is built from source below.
project(RealtimeCoreVoiceQuickStart LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(REALTIMECORE_PACKAGE_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../out/install"
CACHE PATH "Directory containing RealtimeCore/ (install prefix or extracted package)")
set(REALTIMECORE_MSVC_RUNTIME "md" CACHE STRING "MSVC runtime of the artifacts to link (mt, md or mtd)")
set_property(CACHE REALTIMECORE_MSVC_RUNTIME PROPERTY STRINGS mt md mtd)
if(MSVC)
if(REALTIMECORE_MSVC_RUNTIME STREQUAL "mt")
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded")
elseif(REALTIMECORE_MSVC_RUNTIME STREQUAL "md")
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDLL")
elseif(REALTIMECORE_MSVC_RUNTIME STREQUAL "mtd")
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDebug")
else()
message(FATAL_ERROR "REALTIMECORE_MSVC_RUNTIME must be mt, md or mtd (got '${REALTIMECORE_MSVC_RUNTIME}')")
endif()
endif()
find_package(RealtimeCore REQUIRED
PATHS "${REALTIMECORE_PACKAGE_ROOT}"
NO_DEFAULT_PATH
CMAKE_FIND_ROOT_PATH_BOTH)
if(NOT RealtimeCore_VOICE_FOUND)
message(FATAL_ERROR "The RealtimeCore package at ${REALTIMECORE_PACKAGE_ROOT} carries no Voice library.")
endif()
# PortAudio's v19.7.0 CMakeLists asks for CMake 3.1, which CMake 4 refuses, and predates
# CMP0091, without which it ignores CMAKE_MSVC_RUNTIME_LIBRARY and compiles against a
# different CRT than the rest of the link. Raising its policy version fixes both.
include(FetchContent)
set(CMAKE_POLICY_VERSION_MINIMUM 3.15)
set(PA_BUILD_SHARED OFF)
FetchContent_Declare(portaudio
GIT_REPOSITORY https://github.com/PortAudio/portaudio.git
GIT_TAG v19.7.0
GIT_SHALLOW TRUE)
FetchContent_MakeAvailable(portaudio)
add_executable(voice_quickstart main.cpp)
# RealtimeCore::Voice brings RealtimeCore::Matchmaking and everything beneath it.
target_link_libraries(voice_quickstart PRIVATE RealtimeCore::Voice portaudio_static)
The example builds against an extracted SDK package. REALTIMECORE_PACKAGE_ROOT is the directory that contains RealtimeCore/, and REALTIMECORE_MSVC_RUNTIME (mt, md or mtd) picks the matching MSVC runtime on Windows:
Bash
cmake -S . -B build -DREALTIMECORE_PACKAGE_ROOT=<package root> -DREALTIMECORE_MSVC_RUNTIME=mt
cmake --build build --config Release
Two instances with the same App Id talk to each other. With --echo, a single instance hears its own voice back through the server:
Bash
voice_quickstart <your-voice-app-id>
voice_quickstart <your-voice-app-id> --echo
The App Id can also come from the PHOTON_APPID environment variable, and Enter quits.
A running instance prints:
Plain Old Text
joined room cd55792d-7044-4b03-9346-3ce264bdf228 as player 1
talking -- press Enter to quit
voice 1 of player 1 started (echo)
mic 0.00 sending remote voices 1 frames sent 48 received 46 lost 0
mic 0.01 sending remote voices 1 frames sent 99 received 96 lost 0
Next Steps
- Voice Client: the service loop, room lifecycle and shutdown order
- Local Voices: stream format, transmit control and delivery options
- Remote Voices: the playback buffer and its delays
- Audio Integration: threading, sample formats and latency
Last updated on
Back to top