Skip to content

Commit

Permalink
fix(player): event trackEnd not emitted when playing track while al…
Browse files Browse the repository at this point in the history
…ready playing
  • Loading branch information
larsrickert committed Aug 6, 2022
1 parent 67a6539 commit cdc809a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
20 changes: 17 additions & 3 deletions src/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,13 @@ export class Player extends TypedEmitter<PlayerEvents> {
super();

this.audioPlayer.on("stateChange", async (oldState, newState) => {
// the following player events are based on discord voice life cycle, see: https://discordjs.guide/voice/audio-player.html#life-cycle
const newTrack =
newState.status !== AudioPlayerStatus.Idle
? (newState.resource as typeof this.audioResource)?.metadata.track
: undefined;

// check if new track has started (will also be emitted when current track has been seeked)
// see: https://discordjs.guide/voice/audio-player.html#life-cycle
if (
newState.status === AudioPlayerStatus.Playing &&
oldState.status === AudioPlayerStatus.Buffering &&
Expand All @@ -62,12 +62,26 @@ export class Player extends TypedEmitter<PlayerEvents> {
this.emit("trackStart", { ...newTrack });
}

// console.log(oldState.status, newState.status);

// check if track has ended (will NOT be emitted when player was destroyed while playing)
const playingTrackEnded =
oldState.status === AudioPlayerStatus.Playing &&
![AudioPlayerStatus.Paused, AudioPlayerStatus.AutoPaused].includes(
newState.status
);
const pausedTrackEnded =
oldState.status === AudioPlayerStatus.Paused &&
newState.status === AudioPlayerStatus.Buffering;

if (playingTrackEnded || pausedTrackEnded) {
this.emit("trackEnd");
}

if (
newState.status === AudioPlayerStatus.Idle &&
oldState.status !== AudioPlayerStatus.Idle
) {
this.emit("trackEnd");

// current track ended
const nextTrack = await this.getNextTrack();

Expand Down
5 changes: 4 additions & 1 deletion src/types/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import { PlayerEngine, Track } from "./engines";
export interface PlayerEvents {
/** Emitted after a new track has started. */
trackStart: (track: Track) => void;
/** Emitted after a track has ended and before a new track has started (if any). */
/**
* Emitted after a track has ended and before a new track has started.
* Will not be emitted when player is stopped while playing (`destroyed` event).
*/
trackEnd: () => void;
/**
* Emitted after the player was destroyed/player left voice channel.
Expand Down

0 comments on commit cdc809a

Please sign in to comment.