Skip to content

Commit

Permalink
improve: audio ending detection
Browse files Browse the repository at this point in the history
This commit takes improvements of audio ending detections even further, now properly detecting it and being resistent against network lags.
  • Loading branch information
ThePedroo committed Apr 7, 2024
1 parent fc0ff41 commit ed60efb
Show file tree
Hide file tree
Showing 5 changed files with 14 additions and 10 deletions.
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ client.ws.on('VOICE_SERVER_UPDATE', (data) => {
endpoint: buffer.endpoint
})

// Stream must end with a 0 (as Buffer)
connection.connect(() => connection.play(stream))
}
})
Expand Down
4 changes: 4 additions & 0 deletions docs/Connection/play.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,8 @@ Nothing.

- Requires the stream to end with 0 (as Buffer) to stop playing.

### 2.0.1

- Instead of requiring the stream to end with 0, it now requires the stream to emit the `end` event when it finished buffering.

</details>
13 changes: 7 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ const DISCORD_CLOSE_CODES = {
4014: { error: false },
4015: { reconnect: true }
}
const STREAM_END = Buffer.alloc(1)

const ssrcs = {}

Expand Down Expand Up @@ -124,7 +123,7 @@ class Connection extends EventEmitter {

this.ws = new WebSocket(`wss://${this.voiceServer.endpoint}/?v=4`, {
headers: {
'User-Agent': 'DiscordBot (https://github.com/PerformanC/voice, 2.0.0)'
'User-Agent': 'DiscordBot (https://github.com/PerformanC/voice, 2.0.1)'
}
})

Expand Down Expand Up @@ -408,15 +407,17 @@ class Connection extends EventEmitter {
this._setSpeaking(1 << 0)

const packetBuffer = Buffer.allocUnsafe(12)
let shouldStop = false

this.playInterval = setInterval(() => {
const chunk = this.audioStream.read(OPUS_FRAME_SIZE)

if (chunk === STREAM_END) return this.stop('finished')
if (!chunk) return;

this.sendAudioChunk(packetBuffer, chunk)
if (!chunk && shouldStop) return this.stop('finished')

if (chunk) this.sendAudioChunk(packetBuffer, chunk)
}, OPUS_FRAME_DURATION)

this.audioStream.once('end', () => shouldStop = true)
}

_destroyConnection(code, reason) {
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@performanc/voice",
"version": "2.0.0",
"version": "2.0.1",
"description": "Performant Discord voice API client for ES6 Node.js",
"main": "index.js",
"type": "module",
Expand Down

0 comments on commit ed60efb

Please sign in to comment.