DiscordPHP-Voice Documentation

Client extends VoiceClient
in package

The Discord voice client.

Tags
since
10.19.0

Table of Contents

Constants

MICROPHONE  : mixed = 1 << 0
Normal transmission of voice audio.
NOT_SPEAKING  : mixed = 0
Not speaking.
PRIORITY_SPEAKER  : mixed = 1 << 2
Priority speaker, lowering audio of other speakers.
SOUNDSHARE  : mixed = 1 << 1
Transmission of context audio for video, no speaking indicator.

Properties

$buffer  : Buffer|null
Audio Buffer.
$channel  : Channel
$clientsConnected  : array<string|int, mixed>
Current clients connected to the voice chat.
$data  : array<string|int, mixed>
$deaf  : bool
$discord  : Discord
$dnsConfig  : Config|string|null
The Config for DNS Resolver.
$endpoint  : string|null
The Voice WebSocket endpoint.
$frameSize  : int
The size of audio frames, in milliseconds.
$heartbeat  : TimerInterface|null
The Voice WebSocket heartbeat timer.
$heartbeatInterval  : int|null
The UDP heartbeat interval.
$manager  : Manager|null
$monitorProcessTimer  : TimerInterface
$mute  : bool
$nonce  : int
Independent 32-bit nonce counter used for AES-256-GCM encryption.
$opusdecoder  : OpusDecoderInterface|null
The Opus Decoder instance.
$paused  : bool
Whether the voice client is currently paused.
$readOpusTimer  : TimerInterface|null
readopus Timer.
$ready  : bool
Is the voice client ready?
$receiveStreams  : array<string|int, ReceiveStream>|null
Voice audio receive streams.
$recieveStreams  : array<string|int, ReceiveStream>|null
Voice audio recieve streams.
$reconnecting  : bool
Is the voice client reconnecting?
$sentLoginFrame  : bool
Have we sent the login frame yet?
$seq  : int
The sequence of audio packets being sent.
$speaking  : int
$ssrc  : int|null
The SSRC value.
$startTime  : float|int|null
The time we started sending packets.
$streamTime  : int
Time in which the streaming started.
$timestamp  : int
The timestamp of the last packet.
$udp  : null|Socket|UDP
The UDP client instance.
$userClose  : bool
Is the voice client being closed by user?
$users  : array<string|int, User>
Users in the current voice channel.
$voice_sessions  : array<string|int, mixed>|AbstractRepository|null
$voiceDecoders  : array<int, Process>
Collection of voice decoders.
$ws  : WebSocket|null
The voice WebSocket instance.
$audioApplication  : string
The audio application to encode with.
$bitrate  : int
The bitrate to encode with.
$deferred  : Deferred|null
$ffiDecoders  : array<int, OpusFfi>
Per-SSRC OpusFfi decoder instances. Each speaker gets their own persistent decoder so inter-frame codec state is never shared or reset between users.
$recordingFormat  : RecordingFormat|null
The active recording format, set when record() is called with a format.
$recordingOutputPath  : callable(string): string|null
Callback that returns the output file path for a given user ID string, set when record() is called with a non-null $outputPath.
$recordingPcmHandles  : array<int, resource>
Open file handles for raw PCM output keyed by SSRC (populated when record() is called with RecordingFormat::PCM and an output path callback).
$recordingProcesses  : array<int, Process>
Active ffmpeg OGG encoder processes keyed by SSRC (populated when record() is called with RecordingFormat::OGG and an output path callback).
$recordingWriters  : array<int, WavWriter>
Active WavWriter instances keyed by SSRC (populated when record() is called with RecordingFormat::WAV and an output path callback).
$shouldBoot  : bool
$shouldRecord  : bool
Whether the current voice client is enabled to record audio.
$silenceRemaining  : int
Silence Frame Remain Count.
$speakingStatus  : ExCollectionInterface<string|int, Speaking>
Collection of the status of people speaking.
$ssrcToUserId  : array<int, string>
O(1) map from SSRC to user ID, kept in sync with speakingStatus.
$volume  : int
The volume the audio will be encoded with.

Methods

__construct()  : mixed
Constructs the Voice client instance.
__get()  : mixed
Allows read-only access to selected protected properties from outside the class.
boot()  : bool
Boots the voice client and sets up event listeners.
checkForExecutable()  : string|null
Checks if an executable exists on the system.
close()  : void
Closes the voice client.
decryptDaveFrame()  : string|false
Decrypts an incoming Opus frame using DAVE when enabled.
disconnect()  : VoiceClient
Disconnects the discord from the current voice channel.
encryptDaveFrame()  : string
Encrypts an outgoing Opus frame using DAVE when enabled.
getDbVolume()  : float|int
The current playback volume expressed in decibels.
getReceiveStream()  : ReceiveStream|null
Gets a receive voice stream.
getRecieveStream()  : RecieveStream|ReceiveStream|null
Gets a recieve voice stream.
handleAudioData()  : void
Handles raw opus data from the UDP server.
handleVoiceServerChange()  : void
Handles a voice server change.
handleVoiceStateUpdate()  : void
Handles a voice state update.
isReady()  : bool
Returns whether the voice client is ready.
isSpeaking()  : bool
Checks if the user is speaking.
make()  : Client
Creates a new voice client instance statically.
pause()  : void
Pauses the current sound.
playDCAStream()  : PromiseInterface
Plays a DCA stream.
playFile()  : PromiseInterface
Plays a file/url on the voice stream.
playOggStream()  : PromiseInterface
playPcmFile()  : PromiseInterface
Plays a raw PCM file on the voice stream.
playRawStream()  : PromiseInterface
Plays a raw PCM16 stream.
record()  : void
Starts recording incoming voice audio.
setAudioApplication()  : void
Sets the audio application.
setBitrate()  : void
Sets the bitrate.
setData()  : $this
Merges gateway connection data into this client and boots it once `token`, `endpoint`, `session` and `dnsConfig` are all present.
setDecoder()  : void
Sets the Opus decoder.
setMuteDeaf()  : void
Changes your mute and deaf value.
setSpeaking()  : void
Sets the speaking value of the client.
setVolume()  : void
Sets the volume.
start()  : bool
Starts the voice client.
stop()  : void
Stops the current sound.
stopRecording()  : void
Stops an in-progress recording started by {@see record()}.
switchChannel()  : self
Switches voice channels.
unpause()  : void
Unpauses the current sound.
createDecoder()  : void
Creates and initializes a decoder process for the given stream session.
mainSend()  : void
Sends a message to the main websocket.
monitorProcessExit()  : void
Monitor a process for exit and trigger callbacks when it exits.
readDCAOpus()  : void
Reads and processes a single Opus audio frame from a DCA (Discord Compressed Audio) stream.
readOggOpus()  : void
Reads Ogg Opus packets and sends them to the voice server.
removeDecoder()  : void
Removes and closes the voice decoder associated with the given SSRC.
reset()  : void
Resets the voice client.

Constants

MICROPHONE

Normal transmission of voice audio.

public mixed MICROPHONE = 1 << 0

NOT_SPEAKING

Not speaking.

public mixed NOT_SPEAKING = 0

PRIORITY_SPEAKER

Priority speaker, lowering audio of other speakers.

public mixed PRIORITY_SPEAKER = 1 << 2

SOUNDSHARE

Transmission of context audio for video, no speaking indicator.

public mixed SOUNDSHARE = 1 << 1

Properties

$clientsConnected

Current clients connected to the voice chat.

public array<string|int, mixed> $clientsConnected = []

$dnsConfig

The Config for DNS Resolver.

public Config|string|null $dnsConfig

$endpoint

The Voice WebSocket endpoint.

public string|null $endpoint

The endpoint the Voice WebSocket and UDP client will connect to.

$frameSize

The size of audio frames, in milliseconds.

public int $frameSize = 20

The size of audio frames.

$heartbeat

The Voice WebSocket heartbeat timer.

public TimerInterface|null $heartbeat = null

The heartbeat periodic timer.

$heartbeatInterval

The UDP heartbeat interval.

public int|null $heartbeatInterval = null

How often we send a heartbeat packet.

$monitorProcessTimer

public TimerInterface $monitorProcessTimer

$nonce

Independent 32-bit nonce counter used for AES-256-GCM encryption.

public int $nonce = 0

Increments separately from the 16-bit $seq so nonces never repeat after a sequence rollover (~21 min at 50 pkt/s).

$paused

Whether the voice client is currently paused.

public bool $paused = false

$readOpusTimer

readopus Timer.

public TimerInterface|null $readOpusTimer = null

Timer

$ready

Is the voice client ready?

public bool $ready = false

Whether the voice client is ready.

$receiveStreams

Voice audio receive streams.

public array<string|int, ReceiveStream>|null $receiveStreams

Voice audio recieve streams.

$recieveStreams

Voice audio recieve streams.

Use receiveStreams instead.

public array<string|int, ReceiveStream>|null $recieveStreams

Voice audio recieve streams.

$reconnecting

Is the voice client reconnecting?

public bool $reconnecting = false

Whether the voice client is reconnecting.

$sentLoginFrame

Have we sent the login frame yet?

public bool $sentLoginFrame = false

Whether we have sent the login frame.

$seq

The sequence of audio packets being sent.

public int $seq = 0

The sequence of audio packets.

$speaking

public int $speaking = self::NOT_SPEAKING

$ssrc

The SSRC value.

public int|null $ssrc

The SSRC value used for RTP.

$startTime

The time we started sending packets.

public float|int|null $startTime

The time we started sending packets.

$streamTime

Time in which the streaming started.

public int $streamTime = 0

$timestamp

The timestamp of the last packet.

public int $timestamp = 0

The timestamp the last packet was constructed.

$userClose

Is the voice client being closed by user?

public bool $userClose = false

Whether the voice client is being closed by user.

$users

Users in the current voice channel.

public array<string|int, User> $users

Users in the current voice channel.

$voice_sessions

public array<string|int, mixed>|AbstractRepository|null $voice_sessions = null

$voiceDecoders

Collection of voice decoders.

public array<int, Process> $voiceDecoders = []

Voice decoders.

$ws

The voice WebSocket instance.

public WebSocket|null $ws

The voice WebSocket client.

$audioApplication

The audio application to encode with.

protected string $audioApplication = 'audio'

Available: voip, audio (default), lowdelay

The audio application.

$bitrate

The bitrate to encode with.

protected int $bitrate = 128000

Encoding bitrate.

$ffiDecoders

Per-SSRC OpusFfi decoder instances. Each speaker gets their own persistent decoder so inter-frame codec state is never shared or reset between users.

protected array<int, OpusFfi> $ffiDecoders = []

$recordingFormat

The active recording format, set when record() is called with a format.

protected RecordingFormat|null $recordingFormat = null

$recordingOutputPath

Callback that returns the output file path for a given user ID string, set when record() is called with a non-null $outputPath.

protected callable(string): string|null $recordingOutputPath = null

$recordingPcmHandles

Open file handles for raw PCM output keyed by SSRC (populated when record() is called with RecordingFormat::PCM and an output path callback).

protected array<int, resource> $recordingPcmHandles = []

$recordingProcesses

Active ffmpeg OGG encoder processes keyed by SSRC (populated when record() is called with RecordingFormat::OGG and an output path callback).

protected array<int, Process> $recordingProcesses = []

$recordingWriters

Active WavWriter instances keyed by SSRC (populated when record() is called with RecordingFormat::WAV and an output path callback).

protected array<int, WavWriter> $recordingWriters = []

$shouldRecord

Whether the current voice client is enabled to record audio.

protected bool $shouldRecord = false

$silenceRemaining

Silence Frame Remain Count.

protected int $silenceRemaining = 5

Amount of silence frames remaining.

$speakingStatus

Collection of the status of people speaking.

protected ExCollectionInterface<string|int, Speaking> $speakingStatus

Status of people speaking.

$ssrcToUserId

O(1) map from SSRC to user ID, kept in sync with speakingStatus.

protected array<int, string> $ssrcToUserId = []

$volume

The volume the audio will be encoded with.

protected int $volume = 100

The volume that the audio will be encoded in.

Methods

__construct()

Constructs the Voice client instance.

public __construct(Discord $discord, Channel $channel[, array<string|int, mixed>|AbstractRepository|null $voice_sessions = null ][, array<string|int, mixed> $data = [] ][, bool $deaf = false ][, bool $mute = false ][, Deferred|null $deferred = null ][, Manager|null &$manager = null ][, bool $shouldBoot = true ]) : mixed
Parameters
$discord : Discord

The Discord instance.

$channel : Channel
$voice_sessions : array<string|int, mixed>|AbstractRepository|null = null

$discord->voice_sessions, kept as given. Sessions are read from $discord->voice_sessions itself, through VoiceSessions.

$data : array<string|int, mixed> = []
$deaf : bool = false

Default: false

$mute : bool = false

Default: false

$deferred : Deferred|null = null
$manager : Manager|null = null
$shouldBoot : bool = true
Tags
since
8.3.0

$voice_sessions is no longer taken by reference, and may be DiscordPHP's voice session repository.

__get()

Allows read-only access to selected protected properties from outside the class.

public __get(string $name) : mixed
Parameters
$name : string

boot()

Boots the voice client and sets up event listeners.

public boot() : bool
Return values
bool

checkForExecutable()

Checks if an executable exists on the system.

public static checkForExecutable(string $executable) : string|null

Use ProcessAbstract::checkForExecutable() instead.

Parameters
$executable : string
Return values
string|null

close()

Closes the voice client.

public close() : void
Tags
throws
RuntimeException

decryptDaveFrame()

Decrypts an incoming Opus frame using DAVE when enabled.

public decryptDaveFrame(string $frame[, Packet|null $packet = null ]) : string|false
Parameters
$frame : string
$packet : Packet|null = null
Return values
string|false

encryptDaveFrame()

Encrypts an outgoing Opus frame using DAVE when enabled.

public encryptDaveFrame(string $frame) : string
Parameters
$frame : string
Return values
string

getDbVolume()

The current playback volume expressed in decibels.

public getDbVolume() : float|int

Maps the 0-100 linear volume to roughly -100 dB (mute) up to 0 dB (full).

Return values
float|int

handleAudioData()

Handles raw opus data from the UDP server.

public handleAudioData(Packet $voicePacket) : void
Parameters
$voicePacket : Packet

The data from the UDP server.

handleVoiceServerChange()

Handles a voice server change.

public handleVoiceServerChange([array<string|int, mixed> $data = [] ]) : void
Parameters
$data : array<string|int, mixed> = []

New voice server information.

handleVoiceStateUpdate()

Handles a voice state update.

public handleVoiceStateUpdate(VoiceStateUpdate $data) : void

NOTE: This object contains the data as the VoiceStateUpdate Part.

Parameters
$data : VoiceStateUpdate

The WebSocket data.

Tags
see
VoiceStateUpdate

isReady()

Returns whether the voice client is ready.

public isReady() : bool
Return values
bool —

Whether the voice client is ready.

isSpeaking()

Checks if the user is speaking.

public isSpeaking([string|int|null $id = null ]) : bool
Parameters
$id : string|int|null = null

Either the User ID or SSRC (if null, return discords speaking status).

Return values
bool —

Whether the user is speaking.

pause()

Pauses the current sound.

public pause() : void
Tags
throws
RuntimeException

playDCAStream()

Plays a DCA stream.

public playDCAStream(resource|Process|ReadableResourceStream $stream) : PromiseInterface

DCA is now deprecated in DiscordPHP, switch to using playOggStream with raw Ogg Opus.

Parameters
$stream : resource|Process|ReadableResourceStream

The DCA stream to be sent.

Tags
throws
Exception
Return values
PromiseInterface

playFile()

Plays a file/url on the voice stream.

public playFile(string $file[, int $channels = 2 ]) : PromiseInterface

FFmpeg is used to decode the file, so any format ffmpeg supports is accepted (e.g. WAV, OGG Opus, MP3, FLAC). Raw PCM files (.pcm) are NOT supported here because ffmpeg cannot auto-detect the format — use playPcmFile() instead.

Parameters
$file : string

The file/url to play.

$channels : int = 2

Deprecated, Discord only supports 2 channels.

Tags
throws
FileNotFoundException
RuntimeException
Return values
PromiseInterface

playOggStream()

public playOggStream(resource|Process|ReadableResourceStream $stream) : PromiseInterface
Parameters
$stream : resource|Process|ReadableResourceStream

The Ogg Opus stream to be sent.

Tags
throws
RuntimeException
InvalidArgumentException
Return values
PromiseInterface

playPcmFile()

Plays a raw PCM file on the voice stream.

public playPcmFile(string $path[, int $channels = 2 ][, int $audioRate = 48000 ]) : PromiseInterface

This is a convenience wrapper around playRawStream() for files saved as raw signed 16-bit little-endian PCM (e.g. recordings produced by record() with RecordingFormat::PCM).

Parameters
$path : string

Absolute or relative path to the raw PCM file.

$channels : int = 2

Number of audio channels (default: 2 = stereo).

$audioRate : int = 48000

Sample rate in Hz (default: 48000).

Tags
throws
FileNotFoundException

if the file does not exist.

RuntimeException

if the file cannot be opened or audio is already playing.

Return values
PromiseInterface

playRawStream()

Plays a raw PCM16 stream.

public playRawStream(resource|ReadableResourceStream $stream[, int $channels = 2 ][, int $audioRate = 48000 ]) : PromiseInterface
Parameters
$stream : resource|ReadableResourceStream

The stream to be encoded and sent.

$channels : int = 2

How many audio channels the PCM16 was encoded with.

$audioRate : int = 48000

Audio sampling rate the PCM16 was encoded with.

Tags
throws
RuntimeException
InvalidArgumentException

Thrown when the stream passed to playRawStream is not a valid resource.

Return values
PromiseInterface

record()

Starts recording incoming voice audio.

public record([RecordingFormat|null $format = null ][, callable(string): string|null $outputPath = null ]) : void

When called with no arguments, raw PCM and Opus frames are emitted via the channel-pcm and channel-opus events for the caller to handle.

When called with a format and output path callback, the voice client automatically writes per-user audio files. The callback receives the user ID string and must return an absolute or relative file path string.

Supported formats:

  • RecordingFormat::PCM — raw s16le PCM; emits channel-pcm events AND writes raw bytes to per-user files when $outputPath is provided
  • RecordingFormat::WAV — per-user WAV files via pure-PHP WavWriter
  • RecordingFormat::OGG — per-user OGG Opus files via ffmpeg (requires ffmpeg)
Parameters
$format : RecordingFormat|null = null

Output format. Null = PCM events only (no file writing).

$outputPath : callable(string): string|null = null

Callback returning the file path for a given user ID. Required for WAV and OGG formats. Optional for PCM (when provided, raw PCM bytes are written to the file).

Tags
throws
RuntimeException

if already recording.

InvalidArgumentException

if $format is non-null/non-PCM but $outputPath is null.

setAudioApplication()

Sets the audio application.

public setAudioApplication(string $app) : void
Parameters
$app : string

The audio application to set.

Tags
throws
DomainException
RuntimeException

setBitrate()

Sets the bitrate.

public setBitrate(int $bitrate) : void
Parameters
$bitrate : int

The bitrate to set.

Tags
throws
DomainException
RuntimeException

setData()

Merges gateway connection data into this client and boots it once `token`, `endpoint`, `session` and `dnsConfig` are all present.

public setData(array<string, mixed> $data) : $this
Parameters
$data : array<string, mixed>
Return values
$this

setMuteDeaf()

Changes your mute and deaf value.

public setMuteDeaf(bool $mute, bool $deaf) : void
Parameters
$mute : bool

Whether you should be muted.

$deaf : bool

Whether you should be deaf.

Tags
throws
RuntimeException

setSpeaking()

Sets the speaking value of the client.

public setSpeaking([int $speaking = self::MICROPHONE ]) : void
Parameters
$speaking : int = self::MICROPHONE

Whether the client is speaking or not.

Tags
throws
RuntimeException

setVolume()

Sets the volume.

public setVolume(int $volume) : void
Parameters
$volume : int

The volume to set.

Tags
throws
DomainException
RuntimeException

start()

Starts the voice client.

public start() : bool
Return values
bool

stop()

Stops the current sound.

public stop() : void
Tags
throws
RuntimeException

stopRecording()

Stops an in-progress recording started by {@see record()}.

public stopRecording() : void

Finalises every per-user writer, closes recording processes and PCM handles, and clears all receive-stream, decoder and speaking state.

Tags
throws
RuntimeException

if no recording is in progress.

switchChannel()

Switches voice channels.

public switchChannel(null|Channel $channel) : self
Parameters
$channel : null|Channel

The channel to switch to.

Tags
throws
InvalidArgumentException
Return values
self

unpause()

Unpauses the current sound.

public unpause() : void
Tags
throws
RuntimeException

createDecoder()

Creates and initializes a decoder process for the given stream session.

protected createDecoder(object $ss) : void
Parameters
$ss : object

The stream session object containing information such as SSRC and user ID.

mainSend()

Sends a message to the main websocket.

protected mainSend(Payload $data) : void
Parameters
$data : Payload

The data to send to the main WebSocket.

monitorProcessExit()

Monitor a process for exit and trigger callbacks when it exits.

protected monitorProcessExit(Process $process, object $ss) : void
Parameters
$process : Process

The process to monitor

$ss : object

The speaking status object

readDCAOpus()

Reads and processes a single Opus audio frame from a DCA (Discord Compressed Audio) stream.

protected readDCAOpus(Deferred $deferred) : void
Parameters
$deferred : Deferred

A promise that will be resolved when the reading process completes or fails.

readOggOpus()

Reads Ogg Opus packets and sends them to the voice server.

protected readOggOpus(Deferred $deferred, OggStream &$ogg, int &$loops) : void
Parameters
$deferred : Deferred

The deferred promise.

$ogg : OggStream

The Ogg stream to read packets from.

$loops : int

The number of loops that have been executed.

removeDecoder()

Removes and closes the voice decoder associated with the given SSRC.

protected removeDecoder(object $ss) : void
Parameters
$ss : object

An object containing the SSRC (Synchronization Source identifier). Expected to have a property 'ssrc'.

On this page

Search results