29 Commits
Author SHA1 Message Date
fraujulian 51d738a442 fix: rollout 2026-05-23 21:17:49 +02:00
fraujulian db7de9c04d fix: rollout 2026-05-23 21:12:11 +02:00
fraujulian eaf86f948b fix: rollout 2026-05-23 20:13:04 +02:00
fraujulian d4f92e1eac fix: rollout 2026-05-23 20:02:53 +02:00
fraujulian 9eace0838b fix: rollout 2026-05-23 19:56:12 +02:00
fraujulian 5cc7127a5a chore: updated dependencies 2026-05-23 19:48:54 +02:00
fraujulian 7923b917d8 chore: updated dependencies 2026-05-23 19:44:52 +02:00
fraujulian 78cbf3f233 refactor: husky 2026-05-23 19:38:05 +02:00
fraujulian 4cc9774ff5 feat: github release task 2026-05-23 19:37:12 +02:00
fraujulian 6962d87f24 feat & improvements & refactor: new structure, better garbage collection, better docs, better performance, added tests 2026-05-23 19:26:59 +02:00
fraujulianandGitHub 966db49e37 Add LICENSE file 2026-05-23 19:07:24 +02:00
fraujulianandGitHub 707822e43d Merge pull request #31 from FrauJulian/dependabot/npm_and_yarn/typescript-eslint/parser-8.50.1
Bump @typescript-eslint/parser from 8.50.0 to 8.50.1
2025-12-23 22:45:21 +01:00
fraujulianandGitHub 29f51c5ff0 Merge pull request #32 from FrauJulian/dependabot/npm_and_yarn/typescript-eslint/eslint-plugin-8.50.1
Bump @typescript-eslint/eslint-plugin from 8.50.0 to 8.50.1
2025-12-23 22:45:14 +01:00
dependabot[bot]andGitHub ee676212ab Bump @typescript-eslint/eslint-plugin from 8.50.0 to 8.50.1
Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 8.50.0 to 8.50.1.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.50.1/packages/eslint-plugin)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-version: 8.50.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-23 13:20:33 +00:00
dependabot[bot]andGitHub 5496514dab Bump @typescript-eslint/parser from 8.50.0 to 8.50.1
Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 8.50.0 to 8.50.1.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.50.1/packages/parser)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-version: 8.50.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-23 13:20:21 +00:00
fraujulianandGitHub 1e08cddc61 Merge pull request #30 from FrauJulian/dependabot/npm_and_yarn/types/node-25.0.3
Bump @types/node from 25.0.2 to 25.0.3
2025-12-18 08:00:19 +01:00
dependabot[bot]andGitHub d07efd73a5 Bump @types/node from 25.0.2 to 25.0.3
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 25.0.2 to 25.0.3.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.0.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-17 13:25:52 +00:00
fraujulianandGitHub 4447437fd2 Update README for clarity and formatting 2025-12-17 08:20:50 +01:00
fraujulianandGitHub 199f9f84c5 Merge pull request #29 from FrauJulian/20-gigantic-update
Gigantic Update - A lot bug fixes and refactorings.
2025-12-16 16:05:24 +01:00
Lechner Julian - FrauJulian 78bc4b4f24 eslint changes; 2025-12-16 16:02:07 +01:00
Lechner Julian - FrauJulian b0dc3ba52b Added issue templates; Removed packet managers, switched to npm; Fixed a lot of Bugs; Added new Versioning; Added types and reworked docs; Refactored project structure; 2025-12-16 16:01:33 +01:00
fraujulianandGitHub 431c720162 Create SECURITY.md 2025-12-16 12:02:18 +01:00
fraujulianandGitHub 309eb75716 Configure Dependabot for npm and daily updates 2025-12-16 11:58:05 +01:00
Lechner Julian - FrauJulian ba9709ddd1 Updated types 2025-10-10 18:48:22 +02:00
fraujulianandGitHub bac8b41cb9 Merge pull request #19 from FrauJulian/fraujulian
Updated types;
2025-10-10 18:30:25 +02:00
Lechner Julian - FrauJulian ecc3189054 Updated pre-commit 2025-10-10 18:29:28 +02:00
Lechner Julian - FrauJulian 96ee35c1e4 Updated typing export/import; 2025-10-10 18:27:43 +02:00
Lechner Julian - FrauJulian f712ea73d7 Merge remote-tracking branch 'origin/fraujulian' into fraujulian 2025-10-10 18:26:30 +02:00
Lechner Julian - FrauJulian 21d8894629 Updated typing export/import; 2025-10-10 18:25:24 +02:00
38 changed files with 12434 additions and 22423 deletions
+9
View File
@@ -0,0 +1,9 @@
*.ts text eol=crlf linguist-language=TypeScript
*.tsx text eol=crlf linguist-language=TypeScript
*.mts text eol=crlf linguist-language=TypeScript
*.cts text eol=crlf linguist-language=TypeScript
*.js text eol=crlf linguist-language=JavaScript
*.jsx text eol=crlf linguist-language=JavaScript
*.mjs text eol=crlf linguist-language=JavaScript
*.cjs text eol=crlf linguist-language=JavaScript
+42
View File
@@ -0,0 +1,42 @@
name: 🐛 Bug Report
description: Report a bug or unexpected behavior
title: '🐛 [BUG]: '
body:
- type: textarea
id: information
attributes:
label: Information
description: Provide all information about the issue.
placeholder: 'What happened? What did you expect to happen?'
validations:
required: false
- type: textarea
id: steps
attributes:
label: Steps to Reproduce
description: Step-by-step instructions to reproduce the issue.
placeholder: |
1. Go to ...
2. Click on ...
3. Observe ...
validations:
required: false
- type: textarea
id: logs
attributes:
label: Logs or Error Messages
description: Paste any relevant console output, stack traces, or screenshots.
placeholder: 'Console output, stacktrace, or screenshots here'
validations:
required: false
- type: input
id: occurrence
attributes:
label: Occurrence Version
description: Specify in which version the issue occurred
placeholder: 'v0.1.TTMMJJ-hhmm'
validations:
required: true
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
+29
View File
@@ -0,0 +1,29 @@
name: 💡 Enhancement
description: Suggest a new feature or improvement
title: '💡 [ENHANCEMENT]: '
body:
- type: textarea
id: description
attributes:
label: Description
description: Describe the new feature or improvement!
placeholder: 'What problem does it solve or what value does it add?'
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed Solution
placeholder: 'Describe how the feature should work.'
validations:
required: false
- type: input
id: implementation
attributes:
label: Implementation Version
description: Specify in which version the enhancement should be released.
placeholder: 'v0.1'
validations:
required: true
+39
View File
@@ -0,0 +1,39 @@
name: ⚙️ Improvement
description: Suggest an improvement to existing functionality, code quality, or performance
title: '⚙️ [Improvement]: '
body:
- type: textarea
id: context
attributes:
label: Current Situation / Context
description: Describe the current behavior or implementation that could be improved.
placeholder: 'Currently, the system loads all users at once, which slows down response time.'
validations:
required: false
- type: textarea
id: proposal
attributes:
label: Proposed Improvement
description: Describe your proposed change or improvement in detail.
placeholder: 'Implement pagination for user loading to reduce memory usage and response time.'
validations:
required: false
- type: textarea
id: benefits
attributes:
label: Expected Benefits
description: Explain how this improvement will help (e.g., better performance, cleaner code, easier maintenance).
placeholder: 'Faster load times, improved scalability, and reduced database load.'
validations:
required: false
- type: input
id: implementation
attributes:
label: Implementation Version
description: Specify in which version the improvement should be released.
placeholder: 'v0.1'
validations:
required: true
+11
View File
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: 'npm' # See documentation for possible values
directory: '/' # Location of package manifests
schedule:
interval: 'daily'
+75 -27
View File
@@ -1,39 +1,87 @@
name: Build Rollout
name: Release and Deploy Build
on:
workflow_dispatch:
workflow_dispatch:
permissions:
id-token: write
contents: read
contents: write
jobs:
build:
runs-on: ubuntu-latest
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: use NodeJS v22.12.0
uses: actions/setup-node@v4
with:
node-version: '22.12.0'
registry-url: 'https://registry.npmjs.org'
always-auth: true
- name: Use NodeJS v24.14.0
uses: actions/setup-node@v6
with:
node-version: '24.14.0'
registry-url: 'https://registry.npmjs.org'
package-manager-cache: false
- name: Create .npmrc
run: echo "//registry.npmjs.org/:_authToken=\${NPM_TOKEN}" > ~/.npmrc
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Install Dependencies
run: npm ci
- name: Install Dependencies
run: npm install
- name: Set Release Version
id: version
run: npm run release:version
- name: run Rollout Build
run: npm run build
- name: Export Release Version
id: release_version
run: |
package_version="$(node -p "require('./package.json').version")"
echo "tag=${package_version}" >> "$GITHUB_OUTPUT"
- name: Publish Library
run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Run Build
run: npm run build
- name: Publish Library
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Create GitHub release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_TAG: v${{ steps.release_version.outputs.tag }}
run: |
git fetch --force --tags
previous_tag="$(gh api repos/${{ github.repository }}/releases --paginate --jq '.[] | select(.draft == false) | .tag_name' | grep -Fxv "$RELEASE_TAG" | head -n 1 || true)"
if [ -n "$previous_tag" ]; then
if git rev-parse --verify --quiet "${previous_tag}^{commit}" >/dev/null; then
commit_messages="$(git log --reverse --format='- %s' "${previous_tag}..${GITHUB_SHA}")"
else
commit_messages="$(git log --reverse --format='- %s' "${GITHUB_SHA}")"
fi
full_changelog="https://github.com/${{ github.repository }}/compare/${previous_tag}...${RELEASE_TAG}"
else
commit_messages="$(git log --reverse --format='- %s' "${GITHUB_SHA}")"
full_changelog=""
fi
if [ -z "$commit_messages" ]; then
commit_messages='- No commits since the previous release'
fi
{
echo '## Changes'
echo
printf '%s\n' "$commit_messages"
echo
if [ -n "$full_changelog" ]; then
echo "**Full Changelog**: ${full_changelog}"
fi
} > release-notes.md
if gh release view "$RELEASE_TAG" >/dev/null 2>&1; then
gh release edit "$RELEASE_TAG" --title "$RELEASE_TAG" --notes-file release-notes.md
else
gh release create "$RELEASE_TAG" --target "${GITHUB_SHA}" --title "$RELEASE_TAG" --notes-file release-notes.md
fi
+22 -15
View File
@@ -1,23 +1,30 @@
name: Build Validation
on:
pull_request:
types: [opened, synchronize, reopened]
workflow_dispatch:
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: use NodeJS v22.16.0
uses: actions/setup-node@v4
with:
node-version: '22.16.0'
- name: use NodeJS v24.14.0
uses: actions/setup-node@v4
with:
node-version: '24.14.0'
- name: Install Dependencies
run: npm install
- name: Install Dependencies
run: npm ci
- name: run Rollout Build
run: npm run build
- name: Run Checks
run: npm run check
- name: Run Build
run: npm run build
+1 -2
View File
@@ -1,3 +1,2 @@
#!/usr/bin/env sh
npm run format || exit 1
npm run lint:fix || exit 1
npm run check || exit 1
+24 -5
View File
@@ -1,10 +1,29 @@
.idea
.git
.github
.git
.idea
.vscode
dist
node_modules
.husky
src
set-version.js
README.md
SECURITY.md
CODEOWNERS
.gitignore
.npmignore
node_modules
src
README.md
.prettierignore
.prettierrc
.gitattributes
tsconfig.json
tsconfig.eslint.json
tsup.config.ts
eslint.config.js
eslint.config.typeaware.cjs
package-lock.json
+5
View File
@@ -0,0 +1,5 @@
node_modules
dist
.git
.idea
.vscode
+11 -11
View File
@@ -1,13 +1,13 @@
{
"printWidth": 140,
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"trailingComma": "all",
"semi": true,
"arrowParens": "always",
"bracketSpacing": true,
"bracketSameLine": false,
"quoteProps": "as-needed",
"endOfLine": "crlf"
"printWidth": 120,
"tabWidth": 4,
"useTabs": false,
"singleQuote": true,
"trailingComma": "all",
"semi": true,
"arrowParens": "always",
"bracketSpacing": true,
"bracketSameLine": false,
"quoteProps": "as-needed",
"endOfLine": "auto"
}
+577 -420
View File
File diff suppressed because it is too large Load Diff
+281 -86
View File
@@ -1,120 +1,315 @@
# Discord Audio Stream
[![npm](https://img.shields.io/npm/dw/discord-audio-stream)](http://npmjs.org/package/discord-audio-stream)
![GitHub package.json version](https://img.shields.io/github/package-json/v/FrauJulian/discord-audio-stream)
![latest release](https://img.shields.io/badge/dynamic/json?label=release&query=$.name&url=https%3A%2F%2Fapi.github.com%2Frepos%2FFrauJulian%2Fdiscord-audio-stream%2Freleases%2Flatest&color=blue)
![GitHub Repo stars](https://img.shields.io/github/stars/FrauJulian/discord-audio-stream?style=social)
**This module is designed to work with [discord.js/voice](https://www.npmjs.com/package/@discordjs/voice) v0.18. This
package doesn't support older
versions!**
> **Designed for 24/7 Discord audio playback.**
> `discord-audio-stream` is a small TypeScript library for managed Discord voice playback through
> `@discordjs/voice` and ffmpeg.
Discord voice streams need careful lifecycle handling. This package manages the voice connection, ffmpeg process,
raw PCM resource creation, optional reconnect renewal, and predictable cleanup so your bot code stays small and readable.
> **Recommended best practice:**
> Keep one `AudioManager` per guild, usually in a `Map<string, AudioManager>`. Update the connection or source through
> `setConnection()` and `setSource()`, then call `start()`. When playback stops, call `stop()`. When the manager will not
> be reused, call `dispose()` to release timers, streams, ffmpeg, and the voice connection.
> **For large bots:**
> Queue many simultaneous starts, for example with [`p-queue`](https://www.npmjs.com/package/p-queue), so the host does
> not spawn too many ffmpeg processes in the same tick.
## 👋 Support
Please create an [issue](https://github.com/FrauJulian/DiscordAudioStreamNPM/issues) on github or write [
`fraujulian`](https://discord.com/users/860206216893693973) on discord!
Please create an [issue](https://github.com/FrauJulian/Discord-Audio-Stream/issues) on GitHub or contact
[`fraujulian`](https://discord.com/users/860206216893693973) on Discord.
## 📝 Usage
### Install
### Installation
> **Supported package managers:** npm, yarn, pnpm, bun
**Node.js `22.12.0` or newer is required.**
#### Recommended:
Install the library and the required voice packages:
```bash
npm install discord-audio-stream @snazzah/davey @discordjs/opus
yarn add discord-audio-stream @snazzah/davey @discordjs/opus
pnpm add discord-audio-stream @snazzah/davey @discordjs/opus
bun add discord-audio-stream @snazzah/davey @discordjs/opus
npm install discord-audio-stream @discordjs/voice prism-media @snazzah/davey opusscript
```
You need `@snazzah/davey` and one of the encryption libraries to run this package!
`libsodium-wrappers` is optional. Install it only when your runtime does not support `aes-256-gcm`:
**Encryption Libraries (npm install):**
> You only need to install one of these libraries if your system does not support `aes-256-gcm` (verify by running
> `require('node:crypto').getCiphers().includes('aes-256-gcm')`).
- `sodium-native`
- `sodium`
- `@stablelib/xchacha20poly1305`
- `@noble/ciphers`
- `libsodium-wrappers`
**Opus Libraries (npm install):**
- `@discordjs/opus`
- `opusscript`
**FFmpeg:**
- [`FFmpeg`](https://ffmpeg.org/) (installed and added to environment)
- `ffmpeg-static`
### Create Instance
```js
let audioManager = new AudioManager();
```bash
node -e "console.log(require('node:crypto').getCiphers().includes('aes-256-gcm'))"
npm install libsodium-wrappers
```
or (with parameters)
For bundled ffmpeg support, install `ffmpeg-static` and use `ffmpeg.mode: 'static'`:
```js
let audioManager = new AudioManager(
{
VoiceChannelId: 0, //voice channel id where to play music
GuildId: 0, //guild id
VoiceAdapter: 0, //guild VoiceAdapter
},
{
ResourceType: '', //resource type like link or file
Resource: '', //auto play link or file name
},
);
```bash
npm install ffmpeg-static
```
### Properties of the AudioManager
If ffmpeg is already available on the host PATH, use `ffmpeg.mode: 'native'`.
#### Properties
### AudioManager Example
| Callable with | Type | Description |
| ----------------- | ---------------------------- | ----------------------------------------------- |
| `VoiceConnection` | **VoiceConnection** | VoiceConnection instance from discord.js/voice. |
| `AudioPlayer` | **AudioPlayer** | AudioPlayer instance from discord.js/voice. |
| `AudioResource` | **AudioResource** | AudioResource instance from discord.js/voice. |
| `ConnectionData` | **VoiceConnectionDataModel** | Global variable for connection data. |
| `AudioData` | **AudioDataModel** | Global variable for audio data. |
```ts
import { AudioManager } from 'discord-audio-stream';
#### Methods
const manager = new AudioManager({
connection: {
guildId: guild.id,
channelId: voiceChannel.id,
adapterCreator: guild.voiceAdapterCreator,
},
source: {
type: 'url',
url: 'https://example.com/live-stream.mp3',
},
ffmpeg: {
mode: 'native',
},
renewIntervalMs: 5_400_000,
});
| Callable with | Parameters | Return type | Description | |
| ------------------------------ | ------------------------------------------------------- | ----------- | ------------------------------------------------------------- | -------------------------------------- |
| `OverrideVoiceConnectionData` | `connectionData` (type of **VoiceConnectionDataModel**) | void | Method to override global connectionData variable. | |
| `OverrideVoiceAudioDataModel` | `audioData` (type of **VoiceAudioDataModel**) | void | Method to override global audioData variable. | |
| `OverrideRenewInMs` | `renewInMs` (type of int, default value is 5400000) | void | Method to override global renewInMs variable. | |
| `CreateConnection` | `isRenew` (type of boolean, default value is false) | void | Method to join the voice connection. | |
| `PlayAudioOnConnection` | | void | Method to play audio on the existing voice connection. | |
| `PauseAudio` | | void | Method to pause the audio. | |
| `ResumeAudio` | | void | Method to resume the audio. | |
| `StopAudioOnConnection` | | void | Method to stop the audio without destroying voice connection. | |
| `CreateConnectionAndPlayAudio` | | void | Method to join the voice connection and play audio. | |
| `DestroyConnection` | | void | Method to destroy the voice connection. | |
| `Dispose` | | void | Dispose all data in object. | |
| `SetVolume` | `volume` (type of number, 0 - 100 percent) | void | Method to set the audio volume. | Method to set the volume of the audio. |
| `SetMaxListeners` | `maxListeners` (type of number) | void | Method to set the max listeners of the audio stream. | |
await manager.start();
```
##### Types History
For a file source:
- [**VoiceConnection** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/VoiceConnection.ts#L166)
- [**AudioPlayer** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioPlayer.ts#L155)
- [**AudioResource** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioResource.ts#L44)
- [**VoiceConnectionDataModel** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceConnectionDataModel.d.ts#L3)
- [**VoiceAudioDataModel** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceAudioDataModel.d.ts#L1)
```ts
manager.setSource({
type: 'file',
path: 'audio/intro.mp3',
});
## 📋 Contributors:
await manager.start();
```
~ [**FrauJulian - Julian Lechner**](https://fraujulian.xyz/).
Relative file paths are resolved from `process.cwd()`. URL sources are validated before playback starts.
## ⚙️ API
### Constructor
```ts
type AudioManagerOptions = {
ffmpeg?: {
mode?: 'native' | 'static';
executablePath?: string;
inputArgs?: readonly string[];
outputArgs?: readonly string[];
};
connection?: {
guildId: string;
channelId: string;
adapterCreator: DiscordGatewayAdapterCreator;
};
source?: { type: 'url'; url: string } | { type: 'file'; path: string };
renewIntervalMs?: number | false;
connectTimeoutMs?: number;
volume?: {
enabled?: boolean;
initialPercent?: number;
};
};
```
### Defaults
| Option | Default |
| ------------------ | ----------- |
| `ffmpeg.mode` | `'native'` |
| `connectTimeoutMs` | `20_000` |
| `renewIntervalMs` | `5_400_000` |
| `volume.enabled` | `false` |
### Methods
| Method | Description |
| ------------------------ | ---------------------------------------------------------------------------------- |
| `setConnection(options)` | Replaces the voice connection target. |
| `setSource(source)` | Replaces the audio source. |
| `connect()` | Joins the configured Discord voice channel. |
| `play(source?)` | Starts playback on an existing connection. |
| `start()` | Connects and starts playback. |
| `pause()` | Pauses active playback. |
| `resume()` | Resumes paused playback. |
| `stop()` | Stops playback, clears renewal, and destroys the voice connection. |
| `setVolume(percent)` | Sets volume from `0` to `100`; requires `volume.enabled: true`. |
| `dispose()` | Idempotently releases timers, ffmpeg, streams, player state, and voice connection. |
### State
```ts
manager.state; // 'idle' | 'connecting' | 'ready' | 'playing' | 'paused' | 'stopped' | 'disposed'
manager.isPlaying;
manager.isConnected;
```
## 🔊 Audio Options
### Volume
Inline volume has a runtime cost in `@discordjs/voice`, so it is disabled by default.
```ts
const manager = new AudioManager({
connection,
source,
volume: {
enabled: true,
initialPercent: 50,
},
});
await manager.start();
manager.setVolume(25);
```
Calling `setVolume()` without `volume.enabled: true` throws `AudioManagerStateError`.
### ffmpeg Modes
- `mode: 'native'` uses the `ffmpeg` executable from the host environment.
- `mode: 'static'` resolves the optional `ffmpeg-static` package.
- `executablePath` overrides both modes and is useful for Docker images or custom ffmpeg builds.
Default output is raw Discord-compatible PCM: `s16le`, `48000 Hz`, `2 channels`.
You can override ffmpeg arguments through `ffmpeg.inputArgs` and `ffmpeg.outputArgs`. When you override them, you are
responsible for keeping the output compatible with `StreamType.Raw`.
### Renewal
By default, the manager schedules a renewal after `5_400_000 ms` so long-running streams can reconnect periodically.
Set `renewIntervalMs: false` to disable this behavior:
```ts
const manager = new AudioManager({
connection,
source,
renewIntervalMs: false,
});
```
`stop()` and `dispose()` always clear the renewal timer.
## 🧯 Errors
The package exports these error classes:
- `AudioManagerError`
- `AudioManagerConfigError`
- `AudioManagerStateError`
- `FfmpegProcessError`
Configuration problems, such as a missing source or invalid URL, throw `AudioManagerConfigError`. Invalid lifecycle
operations, such as calling `pause()` while nothing is playing, throw `AudioManagerStateError`.
## 📋 Migration From `0.7`
Version `1.0` intentionally breaks the old PascalCase API.
| Old | New |
| -------------------------------------------------------- | ------------------------------------------------------------------- |
| `new AudioManager('Native', renewMs, connection, audio)` | `new AudioManager({ ffmpeg, renewIntervalMs, connection, source })` |
| `OverrideVoiceConnectionData(...)` | `setConnection(...)` |
| `OverrideVoiceAudioDataModel(...)` | `setSource(...)` |
| `CreateConnection()` | `connect()` |
| `PlayAudio()` | `play()` |
| `CreateAndPlay()` | `start()` |
| `PauseAudio()` | `pause()` |
| `ResumeAudio()` | `resume()` |
| `StopConnection()` | `stop()` |
| `SetVolume(...)` | `setVolume(...)` |
| `Dispose()` | `dispose()` |
Old connection data:
```ts
{
VoiceChannelId: voiceChannel.id,
GuildId: guild.id,
VoiceAdapter: guild.voiceAdapterCreator,
}
```
New connection data:
```ts
{
channelId: voiceChannel.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
}
```
Old resource data:
```ts
{
ResourceType: ('Link', Resource, 'https://example.com/audio.mp3');
}
{
ResourceType: ('File', Resource, 'audio/intro.mp3');
}
```
New source data:
```ts
{
type: ('url', url, 'https://example.com/audio.mp3');
}
{
type: ('file', path, 'audio/intro.mp3');
}
```
Old ffmpeg modes:
```ts
'Native';
'Standalone';
```
New ffmpeg modes:
```ts
{
ffmpeg: {
mode: 'native';
}
}
{
ffmpeg: {
mode: 'static';
}
}
```
## 🧑‍💻 Development
```bash
npm ci
npm run check
npm run build
```
`npm run check` runs formatting, linting, type-aware linting, TypeScript type checking, and unit tests.
Release version stamping is separate from normal builds:
```bash
npm run release:version
```
## 📋 Contributors
~ [**FrauJulian - Julian Lechner**](https://fraujulian.xyz/) - CODEOWNER
## 🤝 Enjoy the package?
Give it a star ⭐ on [github](https://github.com/FrauJulian/discord-audio-stream)!
Give it a star ⭐ on [GitHub](https://github.com/FrauJulian/discord-audio-stream)!
+18
View File
@@ -0,0 +1,18 @@
# Security Policy
## Supported Versions
Use this section to tell people about which versions of your project are
currently being supported with security updates.
| Version | Supported |
| ------- | ------------------ |
| 0.1.x | :white_check_mark: |
## Reporting a Vulnerability
Use this section to tell people how to report a vulnerability.
Tell them where to go, how often they can expect to get an update on a
reported vulnerability, what to expect if the vulnerability is accepted or
declined, etc.
-1269
View File
File diff suppressed because it is too large Load Diff
+72 -82
View File
@@ -1,101 +1,91 @@
/** @type {import('eslint').Linter.FlatConfig[]} */
const config = [
// Globale Ignores (ersetzt .eslintignore)
{
ignores: ['dist/', 'node_modules/'],
},
// Haupt-Setup für TS/JS-Dateien
{
files: ['**/*.{ts,tsx,js,cjs,mjs}'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module', // du schreibst TS mit ES-Imports; Laufzeit ist CJS nach Transpile
parser: require('@typescript-eslint/parser'),
parserOptions: {
// schnelles Profil: kein Type-Checker, nur Syntax-Linting
ecmaFeatures: {},
},
{
ignores: ['dist/', 'node_modules/'],
},
plugins: {
'@typescript-eslint': require('@typescript-eslint/eslint-plugin'),
import: require('eslint-plugin-import'),
promise: require('eslint-plugin-promise'),
'unused-imports': require('eslint-plugin-unused-imports'),
n: require('eslint-plugin-n'),
},
{
files: ['**/*.{ts,tsx,js,cjs,mjs}'],
rules: {
/* Basis */
'no-debugger': 'warn',
/* TypeScript */
'@typescript-eslint/consistent-type-imports': ['warn', { prefer: 'type-imports' }],
'@typescript-eslint/no-unused-vars': 'off', // schneller über unused-imports
'unused-imports/no-unused-imports': 'warn',
'unused-imports/no-unused-vars': [
'warn',
{
vars: 'all',
varsIgnorePattern: '^_',
args: 'after-used',
argsIgnorePattern: '^_',
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
parser: require('@typescript-eslint/parser'),
parserOptions: {
ecmaFeatures: {},
},
},
],
'@typescript-eslint/no-explicit-any': 'off', // pragmatisch für großen Bot
/* Imports */
'import/first': 'error',
'import/no-duplicates': 'error',
'import/newline-after-import': 'warn',
'import/no-extraneous-dependencies': [
'error',
{
devDependencies: [
'**/*.config.{js,cjs,mjs,ts}',
'**/scripts/**',
'**/*.test.{ts,js}',
'**/Testing.{ts,js}',
'**/.eslintrc.{js,cjs}',
],
plugins: {
'@typescript-eslint': require('@typescript-eslint/eslint-plugin'),
import: require('eslint-plugin-import'),
promise: require('eslint-plugin-promise'),
'unused-imports': require('eslint-plugin-unused-imports'),
n: require('eslint-plugin-n'),
},
],
/* Node (wir kompilieren TS → CJS; ES-Syntax erlauben) */
'n/no-missing-import': 'off', // TypeScript-Resolver übernimmt
'n/no-unsupported-features/es-syntax': 'off',
rules: {
/* Base */
'no-debugger': 'warn',
/* Promises (Discord-/DB-/HTTP-Logik) */
'promise/catch-or-return': 'warn',
'promise/always-return': 'off',
/* TypeScript */
'@typescript-eslint/consistent-type-imports': ['warn', { prefer: 'type-imports' }],
'@typescript-eslint/no-unused-vars': 'off',
'unused-imports/no-unused-imports': 'warn',
'unused-imports/no-unused-vars': [
'warn',
{ vars: 'all', varsIgnorePattern: '^_', args: 'after-used', argsIgnorePattern: '^_' },
],
'@typescript-eslint/no-explicit-any': 'error',
/* bewusste „Fire-and-forget“-Promises mit `void` */
'no-void': ['warn', { allowAsStatement: true }],
},
/* Imports */
'import/first': 'error',
'import/no-duplicates': 'error',
'import/newline-after-import': 'warn',
'import/no-extraneous-dependencies': [
'error',
{
devDependencies: [
'**/*.config*.{js,cjs,mjs,ts}',
'**/scripts/**',
'**/*.test.{ts,js}',
'**/Testing.{ts,js}',
'**/.eslintrc.{js,cjs}',
],
},
],
settings: {
'import/resolver': {
typescript: {
alwaysTryTypes: true,
// nutzt automatisch deine tsconfig-Pfade
/* Node */
'n/no-missing-import': 'off',
'n/no-unsupported-features/es-syntax': 'off',
/* Promis */
'promise/catch-or-return': 'warn',
'promise/always-return': 'off',
/* „Fire-and-forget“-Promises `void` */
'no-void': ['warn', { allowAsStatement: true }],
},
node: true,
},
},
},
// Reine JS/CJS-Skripte (Build/Hooks) dürfen require/exporte nutzen
{
files: ['**/*.{js,cjs}'],
languageOptions: {
sourceType: 'script',
settings: {
'import/resolver': {
typescript: {
alwaysTryTypes: true,
},
node: true,
},
},
},
rules: {
'n/global-require': 'off',
{
files: ['**/*.{js,cjs}'],
languageOptions: {
sourceType: 'script',
},
rules: {
'n/global-require': 'off',
},
},
},
];
module.exports = config;
+17 -17
View File
@@ -2,24 +2,24 @@
const base = require('./eslint.config.cjs');
const typeAwareLayer = {
files: ['**/*.{ts,tsx}'],
languageOptions: {
parser: require('@typescript-eslint/parser'),
parserOptions: {
project: ['./tsconfig.eslint.json'],
tsconfigRootDir: __dirname,
files: ['**/*.{ts,tsx}'],
languageOptions: {
parser: require('@typescript-eslint/parser'),
parserOptions: {
project: ['./tsconfig.eslint.json'],
tsconfigRootDir: __dirname,
},
},
plugins: {
'@typescript-eslint': require('@typescript-eslint/eslint-plugin'),
},
rules: {
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-misused-promises': ['warn', { checksVoidReturn: false }],
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
},
},
plugins: {
'@typescript-eslint': require('@typescript-eslint/eslint-plugin'),
},
rules: {
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-misused-promises': ['warn', { checksVoidReturn: false }],
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
},
};
module.exports = [...base, typeAwareLayer];
+15
View File
@@ -0,0 +1,15 @@
/** @type {import('jest').Config} */
module.exports = {
clearMocks: true,
moduleFileExtensions: ['ts', 'js', 'json'],
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/**/*.test.ts'],
transform: {
'^.+\\.ts$': [
'ts-jest',
{
tsconfig: '<rootDir>/tsconfig.test.json',
},
],
},
};
+10246 -9853
View File
File diff suppressed because it is too large Load Diff
+109 -88
View File
@@ -1,91 +1,112 @@
{
"name": "discord-audio-stream",
"version": "0.6.17",
"license": "LGPL-2.1-only",
"description": "NodeJS library to make stream any audio on discord easier.",
"exports": {
".": {
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
}
}
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"directories": {
"lib": "src"
},
"scripts": {
"lint": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs",
"lint:fix": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs --fix",
"lint:types": "eslint . --config eslint.config.typeaware.cjs --ext .ts,.tsx",
"format": "prettier --write .",
"format:check": "prettier --check .",
"update:dependencies": "npx npm-check-updates --upgrade && pnpm install && bun install && npm install && yarn install && echo PLEASE delete your node_modules directory and install again with your package manager.",
"update:version": "npm version patch --no-git-tag-version",
"clean:dist": "del-cli dist",
"build": "npm run clean:dist && npm run update:version && tsup",
"prepare": "husky"
},
"repository": "https://github.com/FrauJulian/Discord-Audio-Stream",
"bugs": "https://github.com/FrauJulian/Discord-Audio-Stream/issues",
"funding": "https://ko-fi.com/FrauJulian",
"keywords": [
"discordjs",
"discord.js",
"discordjs/voice",
"audio",
"voice"
],
"contributors": [
"FrauJulian - Lechner Julian <fraujulian@lechner.top>"
],
"lint-staged": {
"*.{ts,tsx,js,cjs,mjs}": [
"eslint --fix",
"prettier --write"
"name": "discord-audio-stream",
"version": "1.0.DDDhhmm",
"license": "LGPL-2.1-only",
"description": "A small Discord voice audio streaming library with managed ffmpeg playback.",
"exports": {
".": {
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
}
}
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"*.{json,md,yml,yaml}": [
"prettier --write"
]
},
"dependencies": {
"@discordjs/voice": "^0.19.0",
"@typescript-eslint/eslint-plugin": "^8.46.0",
"@typescript-eslint/parser": "^8.46.0"
},
"devDependencies": {
"@types/ejs": "^3.1.5",
"@types/node": "^24.7.1",
"del-cli": "^7.0.0",
"eslint": "^9.37.0",
"eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-n": "^17.23.1",
"eslint-plugin-promise": "^7.2.1",
"eslint-plugin-unused-imports": "^4.2.0",
"husky": "^9.1.7",
"npm-check-updates": "^19.0.0",
"prettier": "^3.6.2",
"ts-jest": "^29.4.5",
"tsup": "^8.5.0",
"typescript": "^5.9.3"
},
"engines": {
"node": ">=18"
},
"private": false,
"publishConfig": {
"access": "public"
}
"directories": {
"lib": "src"
},
"scripts": {
"update:dependencies": "npx npm-check-updates --upgrade",
"release:version": "node set-version.js",
"lint": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs",
"lint:fix": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs --fix",
"lint:types": "eslint . --config eslint.config.typeaware.cjs --ext .ts,.tsx",
"format": "prettier --write .",
"format:check": "prettier --check .",
"typecheck": "tsc --noEmit",
"test": "jest --runInBand",
"check": "npm run format:check && npm run lint && npm run lint:types && npm run typecheck && npm run test",
"build": "del-cli dist && tsup && tsc -p tsconfig.build.json && node scripts/copy-dts.cjs",
"prepare": "husky"
},
"repository": {
"type": "git",
"url": "git+https://github.com/FrauJulian/Discord-Audio-Stream.git"
},
"bugs": "https://github.com/FrauJulian/Discord-Audio-Stream/issues",
"funding": "https://ko-fi.com/FrauJulian",
"keywords": [
"discordjs",
"discordjs/voice",
"music",
"voice",
"audio",
"24/7"
],
"contributors": [
"FrauJulian - Lechner Julian <fraujulian@lechner.top>"
],
"lint-staged": {
"*.{ts,tsx,js,cjs,mjs}": [
"eslint --fix",
"prettier --write"
],
"*.{json,md,yml,yaml}": [
"prettier --write"
]
},
"devDependencies": {
"@jest/globals": "^30.4.1",
"@types/ejs": "^3.1.5",
"@types/node": "^25.9.1",
"@typescript-eslint/eslint-plugin": "^8.59.4",
"@typescript-eslint/parser": "^8.59.4",
"del-cli": "^7.0.0",
"eslint": "^9.39.4",
"eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-n": "^18.0.1",
"eslint-plugin-promise": "^7.3.0",
"eslint-plugin-unused-imports": "^4.4.1",
"husky": "^9.1.7",
"jest": "^30.4.2",
"npm-check-updates": "^22.2.0",
"prettier": "^3.8.3",
"ts-jest": "^29.4.11",
"tsup": "^8.5.1",
"typescript": "^6.0.3"
},
"peerDependencies": {
"@discordjs/voice": "^0.19.0",
"@snazzah/davey": "^0.1.8",
"ffmpeg-static": "^5.2.0",
"libsodium-wrappers": "^0.7.15",
"opusscript": "^0.0.8",
"prism-media": "^1.3.5"
},
"peerDependenciesMeta": {
"ffmpeg-static": {
"optional": true
},
"libsodium-wrappers": {
"optional": true
}
},
"engines": {
"node": ">=22.12.0"
},
"private": false,
"publishConfig": {
"access": "public"
}
}
-5870
View File
File diff suppressed because it is too large Load Diff
-3
View File
@@ -1,3 +0,0 @@
ignoredBuiltDependencies:
- esbuild
- unrs-resolver
+11
View File
@@ -0,0 +1,11 @@
const { copyFileSync, existsSync } = require('node:fs');
const { join } = require('node:path');
const declarationFile = join(__dirname, '..', 'dist', 'index.d.ts');
const esmDeclarationFile = join(__dirname, '..', 'dist', 'index.d.mts');
if (!existsSync(declarationFile)) {
throw new Error(`Missing declaration file: ${declarationFile}`);
}
copyFileSync(declarationFile, esmDeclarationFile);
+21
View File
@@ -0,0 +1,21 @@
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8').toString());
const [major, minor] = pkg.version.split('.');
const prefix = `${major}.${minor}.`;
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const dayOfYear = Math.floor(diff / (1000 * 60 * 60 * 24));
const hh = String(now.getHours()).padStart(2, '0');
const mm = String(now.getMinutes()).padStart(2, '0');
const newVersion = `${prefix}${String(dayOfYear).padStart(3, '0')}${hh}${mm}`;
pkg.version = newVersion;
fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2));
console.log('Version set to: ', newVersion);
+235 -137
View File
@@ -1,159 +1,257 @@
import type { AudioPlayer, AudioResource, VoiceConnection } from '@discordjs/voice';
import { createAudioPlayer, createAudioResource, joinVoiceChannel } from '@discordjs/voice';
import { join } from 'node:path';
import type { VoiceAudioDataModel, VoiceConnectionDataModel } from './index.d';
import {
createAudioPlayer,
createAudioResource,
entersState,
joinVoiceChannel,
NoSubscriberBehavior,
StreamType,
VoiceConnectionStatus,
} from '@discordjs/voice';
import { isAbsolute, resolve } from 'node:path';
import { AudioManagerConfigError, AudioManagerStateError } from './errors';
import { startFfmpeg, type FfmpegProcessHandle } from './ffmpeg';
import type {
AudioManagerOptions,
AudioSource,
PlaybackState,
ResolvedAudioSource,
VoiceConnectionOptions,
} from './types';
const DEFAULT_CONNECT_TIMEOUT_MS = 20_000;
const DEFAULT_RENEW_INTERVAL_MS = 5_400_000;
export default class AudioManager {
public VoiceConnection?: VoiceConnection;
public AudioPlayer?: AudioPlayer;
public AudioResource?: AudioResource;
private readonly audioPlayer: AudioPlayer;
protected IsActive?: boolean;
protected IsAudioPlaying?: boolean;
private connection: VoiceConnection | undefined;
private resource: AudioResource | undefined;
private ffmpeg: FfmpegProcessHandle | undefined;
private renewTimer: NodeJS.Timeout | undefined;
private playbackState: PlaybackState = 'idle';
private connectionOptions: VoiceConnectionOptions | undefined;
private audioSource: AudioSource | undefined;
private readonly options: Required<Pick<AudioManagerOptions, 'connectTimeoutMs'>> &
Omit<AudioManagerOptions, 'connectTimeoutMs'>;
protected ConnectionData?: VoiceConnectionDataModel;
protected AudioData?: VoiceAudioDataModel;
private TimeoutHandle?: NodeJS.Timeout;
private RenewInMs?: number;
constructor(connectionData?: VoiceConnectionDataModel, audioData?: VoiceAudioDataModel, renewInMs = 5400000) {
this.RenewInMs = renewInMs;
this.ConnectionData = connectionData;
this.AudioData = audioData;
}
public OverrideRenewInMs(renewInMs: number = 5400000): void {
this.RenewInMs = renewInMs;
}
public OverrideVoiceConnectionData(connectionData: VoiceConnectionDataModel): void {
this.ConnectionData = connectionData;
}
public OverrideVoiceAudioDataModel(audioData: VoiceAudioDataModel): void {
this.AudioData = audioData;
}
public CreateConnection(isRenew: boolean = false): void {
this.CheckIfNull(this.ConnectionData);
if (!isRenew) {
if (this.IsActive) {
this.DestroyConnection(false);
} else {
this.IsActive = true;
}
public constructor(options: AudioManagerOptions = {}) {
this.options = {
...options,
connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
};
this.connectionOptions = options.connection;
this.audioSource = options.source;
this.audioPlayer = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
},
});
}
this.VoiceConnection = joinVoiceChannel({
channelId: this.ConnectionData!.VoiceChannelId.toString(),
guildId: this.ConnectionData!.GuildId.toString(),
adapterCreator: this.ConnectionData!.VoiceAdapter,
});
public get state(): PlaybackState {
return this.playbackState;
}
this.TimeoutHandle = setTimeout((): void => {
this.DestroyConnection(false);
if (this.IsActive) {
this.CreateConnection(true);
public get isPlaying(): boolean {
return this.playbackState === 'playing';
}
if (this.IsAudioPlaying) {
this.PlayAudioOnConnection();
public get isConnected(): boolean {
return Boolean(this.connection);
}
public setConnection(options: VoiceConnectionOptions): void {
this.assertNotDisposed();
this.connectionOptions = options;
}
public setSource(source: AudioSource): void {
this.assertNotDisposed();
this.audioSource = source;
}
public async connect(): Promise<void> {
this.assertNotDisposed();
if (!this.connectionOptions) {
throw new AudioManagerConfigError('Voice connection options are required before connecting.');
}
}
}, this.RenewInMs);
}
public PlayAudioOnConnection(): void {
this.CheckIfNull(this.AudioData);
this.clearRenewTimer();
this.playbackState = 'connecting';
this.connection?.destroy();
this.connection = joinVoiceChannel({
guildId: this.connectionOptions.guildId,
channelId: this.connectionOptions.channelId,
adapterCreator: this.connectionOptions.adapterCreator,
});
this.connection.subscribe(this.audioPlayer);
if (this.AudioData!.ResourceType === 'File') {
this.AudioResource = createAudioResource(join(__dirname, this.AudioData!.Resource), { inlineVolume: true });
} else if (this.AudioData!.ResourceType === 'Link') {
this.AudioResource = createAudioResource(this.AudioData!.Resource, { inlineVolume: true });
} else {
throw new Error('Invalid resource type.');
await entersState(this.connection, VoiceConnectionStatus.Ready, this.options.connectTimeoutMs);
this.playbackState = 'ready';
this.scheduleRenewal();
}
this.AudioPlayer = createAudioPlayer();
this.AudioPlayer.play(this.AudioResource);
public async play(source?: AudioSource): Promise<void> {
this.assertNotDisposed();
this.VoiceConnection!.subscribe(this.AudioPlayer!);
this.IsAudioPlaying = true;
}
if (source) {
this.setSource(source);
}
public StopAudioOnConnection(): void {
if (this.IsAudioPlaying) {
this.DestroyConnection(false);
this.CreateConnection();
} else {
throw new Error('Audio is not playing.');
}
}
if (!this.connection) {
throw new AudioManagerStateError('A voice connection is required before audio can be played.');
}
public PauseAudio(): void {
if (this.IsAudioPlaying) {
this.AudioPlayer!.pause();
this.IsAudioPlaying = false;
} else {
throw new TypeError('Audio is not playing.');
}
}
const resolvedSource = this.resolveSource();
this.stopCurrentPlayback();
this.ffmpeg = startFfmpeg(resolvedSource.input, this.options.ffmpeg);
this.resource = createAudioResource(this.ffmpeg.process.stdout, {
inputType: StreamType.Raw,
inlineVolume: this.options.volume?.enabled === true,
});
public ResumeAudio(): void {
if (!this.IsAudioPlaying) {
this.AudioPlayer!.unpause();
this.IsAudioPlaying = true;
} else {
throw new TypeError('Audio is playing.');
}
}
if (this.options.volume?.enabled === true && this.options.volume.initialPercent !== undefined) {
this.setVolume(this.options.volume.initialPercent);
}
public CreateConnectionAndPlayAudio(): void {
this.CreateConnection();
this.PlayAudioOnConnection();
}
public DestroyConnection(resetValidationParameters: boolean = true): void {
if (this.CheckIfNull(this.VoiceConnection)) return;
this.VoiceConnection!.destroy();
if (resetValidationParameters) {
this.IsActive = false;
this.IsAudioPlaying = false;
}
}
public SetMaxListeners(maxListeners: number): void {
if (this.CheckIfNull(this.VoiceConnection)) return;
this.VoiceConnection!.setMaxListeners(maxListeners);
}
public SetVolume(volumeInPercent: number): void {
if (volumeInPercent < 0 || volumeInPercent > 100) throw new Error('Volume must be between 0 and 100.');
if (this.CheckIfNull(this.VoiceConnection)) return;
this.AudioResource!.volume!.setVolume(volumeInPercent / 100);
}
public Dispose(): void {
this.VoiceConnection = undefined;
this.AudioPlayer = undefined;
this.AudioResource = undefined;
this.IsActive = undefined;
this.IsAudioPlaying = undefined;
this.ConnectionData = undefined;
this.AudioData = undefined;
this.TimeoutHandle = undefined;
this.RenewInMs = undefined;
}
private CheckIfNull<T>(value: T | null): boolean {
if (value === null) {
throw new Error(`${value} cannot be null in this case.`);
this.audioPlayer.play(this.resource);
this.playbackState = 'playing';
}
return true;
}
public async start(): Promise<void> {
await this.connect();
await this.play();
}
public pause(): void {
this.assertNotDisposed();
if (this.playbackState !== 'playing') {
throw new AudioManagerStateError('Audio can only be paused while it is playing.');
}
this.audioPlayer.pause();
this.playbackState = 'paused';
}
public resume(): void {
this.assertNotDisposed();
if (this.playbackState !== 'paused') {
throw new AudioManagerStateError('Audio can only be resumed while it is paused.');
}
this.audioPlayer.unpause();
this.playbackState = 'playing';
}
public async stop(): Promise<void> {
if (this.playbackState === 'disposed') {
return;
}
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
this.connection?.disconnect();
this.connection?.destroy();
this.connection = undefined;
this.playbackState = 'stopped';
}
public setVolume(volumeInPercent: number): void {
this.assertNotDisposed();
if (this.options.volume?.enabled !== true) {
throw new AudioManagerStateError('Volume control requires volume.enabled to be true.');
}
if (volumeInPercent < 0 || volumeInPercent > 100) {
throw new AudioManagerConfigError('Volume must be between 0 and 100 percent.');
}
if (!this.resource?.volume) {
throw new AudioManagerStateError('No audio resource with volume control is currently active.');
}
this.resource.volume.setVolume(volumeInPercent / 100);
}
public dispose(): void {
if (this.playbackState === 'disposed') {
return;
}
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
this.connection?.destroy();
this.connection = undefined;
this.connectionOptions = undefined;
this.audioSource = undefined;
this.playbackState = 'disposed';
}
private resolveSource(): ResolvedAudioSource {
if (!this.audioSource) {
throw new AudioManagerConfigError('Audio source is required before playback can start.');
}
if (this.audioSource.type === 'url') {
try {
return {
input: new URL(this.audioSource.url).toString(),
source: this.audioSource,
};
} catch (error) {
throw new AudioManagerConfigError(`Invalid audio source URL. Cause: ${String(error)}`);
}
}
return {
input: isAbsolute(this.audioSource.path)
? this.audioSource.path
: resolve(process.cwd(), this.audioSource.path),
source: this.audioSource,
};
}
private scheduleRenewal(): void {
const renewIntervalMs = this.options.renewIntervalMs ?? DEFAULT_RENEW_INTERVAL_MS;
if (renewIntervalMs === false) {
return;
}
this.renewTimer = setTimeout(() => {
void this.start();
}, renewIntervalMs);
if (typeof this.renewTimer.unref === 'function') {
this.renewTimer.unref();
}
}
private clearRenewTimer(): void {
if (this.renewTimer) {
clearTimeout(this.renewTimer);
this.renewTimer = undefined;
}
}
private stopCurrentPlayback(): void {
this.resource?.playStream.destroy();
this.resource = undefined;
this.ffmpeg?.stop();
this.ffmpeg = undefined;
}
private assertNotDisposed(): void {
if (this.playbackState === 'disposed') {
throw new AudioManagerStateError('AudioManager has been disposed.');
}
}
}
+19
View File
@@ -0,0 +1,19 @@
export class AudioManagerError extends Error {
public constructor(message: string) {
super(message);
this.name = new.target.name;
}
}
export class AudioManagerConfigError extends AudioManagerError {}
export class AudioManagerStateError extends AudioManagerError {}
export class FfmpegProcessError extends AudioManagerError {
public constructor(
message: string,
public readonly cause?: unknown,
) {
super(message);
}
}
+83
View File
@@ -0,0 +1,83 @@
import { spawn } from 'node:child_process';
import type { ChildProcessByStdio } from 'node:child_process';
import { createRequire } from 'node:module';
import type { Readable } from 'node:stream';
import { AudioManagerConfigError } from './errors';
import type { FfmpegOptions } from './types';
const requireFromCurrentModule = createRequire(__filename);
const DEFAULT_INPUT_ARGS = ['-hide_banner', '-loglevel', 'error', '-nostdin'] as const;
const DEFAULT_OUTPUT_ARGS = ['-vn', '-f', 's16le', '-ar', '48000', '-ac', '2', 'pipe:1'] as const;
const FORCE_KILL_TIMEOUT_MS = 2_000;
export type FfmpegProcessHandle = {
process: ChildProcessByStdio<null, Readable, Readable>;
stop(): void;
};
export function resolveFfmpegExecutable(options: FfmpegOptions = {}): string {
if (options.executablePath?.trim()) {
return options.executablePath;
}
if ((options.mode ?? 'native') === 'native') {
return 'ffmpeg';
}
try {
const executable = requireFromCurrentModule('ffmpeg-static') as unknown;
if (typeof executable === 'string' && executable.length > 0) {
return executable;
}
} catch (error) {
throw new AudioManagerConfigError(
`Unable to resolve ffmpeg-static. Install it or pass ffmpeg.executablePath. Cause: ${String(error)}`,
);
}
throw new AudioManagerConfigError('ffmpeg-static did not expose an executable path.');
}
export function startFfmpeg(input: string, options: FfmpegOptions = {}): FfmpegProcessHandle {
const executable = resolveFfmpegExecutable(options);
const args = [
...(options.inputArgs ?? DEFAULT_INPUT_ARGS),
'-i',
input,
...(options.outputArgs ?? DEFAULT_OUTPUT_ARGS),
];
const childProcess = spawn(executable, args, { stdio: ['ignore', 'pipe', 'pipe'] });
childProcess.once('error', () => undefined);
childProcess.stderr.resume();
return {
process: childProcess,
stop: (): void => {
stopProcess(childProcess);
},
};
}
function stopProcess(childProcess: ChildProcessByStdio<null, Readable, Readable>): void {
childProcess.stdout.destroy();
childProcess.stderr.destroy();
childProcess.removeAllListeners();
if (childProcess.killed || childProcess.exitCode !== null || childProcess.signalCode !== null) {
return;
}
childProcess.kill('SIGTERM');
const forceKillTimeout = setTimeout(() => {
if (!childProcess.killed && childProcess.exitCode === null && childProcess.signalCode === null) {
childProcess.kill('SIGKILL');
}
}, FORCE_KILL_TIMEOUT_MS);
forceKillTimeout.unref();
}
-32
View File
@@ -1,32 +0,0 @@
import type { DiscordGatewayAdapterCreator } from '@discordjs/voice';
export type VoiceConnectionDataModel = {
/**
* The ID of the voice channel to connect to.
*/
VoiceChannelId: string;
/**
* The Id of the guild (server) to connect to.
*/
GuildId: string;
/**
* The adapter creator for the voice connection.
* Can be archived by the guild instance via the voiceAdapterCreator property.
*/
VoiceAdapter: DiscordGatewayAdapterCreator;
};
export type VoiceAudioDataModel = {
/**
* The unique identifier for the audio resource.
*/
ResourceType: 'Link' | 'File';
/**
* The URL or file path of the audio resource.
* any is to be assumed to require(filepath)
*/
Resource: string | any;
};
+10
View File
@@ -1 +1,11 @@
export { default as AudioManager } from './audio-manager';
export { AudioManagerConfigError, AudioManagerError, AudioManagerStateError, FfmpegProcessError } from './errors';
export type {
AudioManagerOptions,
AudioSource,
FfmpegMode,
FfmpegOptions,
PlaybackState,
VoiceConnectionOptions,
VolumeOptions,
} from './types';
+178
View File
@@ -0,0 +1,178 @@
import type { DiscordGatewayAdapterCreator } from '@discordjs/voice';
/**
* Strategy used to resolve the ffmpeg executable.
*
* - `native` uses the `ffmpeg` binary available on the host PATH.
* - `static` resolves the optional `ffmpeg-static` package.
*/
export type FfmpegMode = 'native' | 'static';
/**
* Audio input consumed by ffmpeg.
*
* URL sources are validated through the built-in `URL` constructor before playback starts.
* File sources may be absolute or relative; relative paths are resolved from `process.cwd()`.
*/
export type AudioSource =
| {
/**
* Marks this source as a remote URL.
*/
type: 'url';
/**
* Fully qualified audio URL passed to ffmpeg.
*/
url: string;
}
| {
/**
* Marks this source as a local file path.
*/
type: 'file';
/**
* Absolute file path or path relative to `process.cwd()`.
*/
path: string;
};
/**
* Discord voice channel connection settings.
*/
export type VoiceConnectionOptions = {
/**
* Discord guild/server ID.
*/
guildId: string;
/**
* Discord voice channel ID where audio should be played.
*/
channelId: string;
/**
* Discord voice adapter creator, usually `guild.voiceAdapterCreator` from discord.js.
*/
adapterCreator: DiscordGatewayAdapterCreator;
};
/**
* Public playback lifecycle state exposed by `AudioManager.state`.
*/
export type PlaybackState = 'idle' | 'connecting' | 'ready' | 'playing' | 'paused' | 'stopped' | 'disposed';
/**
* ffmpeg executable and argument configuration.
*/
export type FfmpegOptions = {
/**
* ffmpeg resolution mode.
*
* @defaultValue `'native'`
*/
mode?: FfmpegMode;
/**
* Explicit ffmpeg executable path.
*
* When provided, this value takes precedence over `mode`.
*/
executablePath?: string;
/**
* Arguments placed before `-i <source>`.
*
* Override only when you need full control over ffmpeg input behavior.
*/
inputArgs?: readonly string[];
/**
* Arguments placed after `-i <source>`.
*
* If overridden, the output must remain compatible with `StreamType.Raw`.
*/
outputArgs?: readonly string[];
};
/**
* Optional inline volume control settings.
*/
export type VolumeOptions = {
/**
* Enables Discord voice inline volume support.
*
* Disabled by default because inline volume has runtime overhead.
*
* @defaultValue `false`
*/
enabled?: boolean;
/**
* Initial volume percentage applied when playback starts.
*
* Requires `enabled: true`.
*/
initialPercent?: number;
};
/**
* Constructor options for `AudioManager`.
*/
export type AudioManagerOptions = {
/**
* ffmpeg executable and argument configuration.
*/
ffmpeg?: FfmpegOptions;
/**
* Initial Discord voice connection settings.
*
* May also be supplied later through `setConnection()`.
*/
connection?: VoiceConnectionOptions;
/**
* Initial audio source.
*
* May also be supplied later through `setSource()` or `play(source)`.
*/
source?: AudioSource;
/**
* Milliseconds after which the manager reconnects and restarts playback.
*
* Set to `false` to disable renewal.
*
* @defaultValue `5_400_000`
*/
renewIntervalMs?: number | false;
/**
* Maximum milliseconds to wait for the Discord voice connection to become ready.
*
* @defaultValue `20_000`
*/
connectTimeoutMs?: number;
/**
* Optional inline volume configuration.
*/
volume?: VolumeOptions;
};
/**
* Internal normalized audio source passed to ffmpeg.
*/
export type ResolvedAudioSource = {
/**
* Validated URL or absolute file path passed as ffmpeg input.
*/
input: string;
/**
* Original source configuration.
*/
source: AudioSource;
};
+216
View File
@@ -0,0 +1,216 @@
import { jest, describe, beforeEach, afterEach, it, expect } from '@jest/globals';
import { sep } from 'node:path';
import { PassThrough } from 'node:stream';
import AudioManager from '../src/audio-manager';
import { AudioManagerConfigError, AudioManagerStateError } from '../src';
import { startFfmpeg } from '../src/ffmpeg';
import type { AudioSource, VoiceConnectionOptions } from '../src';
const mockAudioPlayer = {
play: jest.fn(),
pause: jest.fn(),
unpause: jest.fn(),
stop: jest.fn(),
};
const mockConnection = {
subscribe: jest.fn(),
disconnect: jest.fn(),
destroy: jest.fn(),
};
const mockAudioResource = {
playStream: {
destroy: jest.fn(),
},
volume: {
setVolume: jest.fn(),
},
};
const mockFfmpegHandle = {
process: {
stdout: new PassThrough(),
},
stop: jest.fn(),
};
jest.mock('@discordjs/voice', () => ({
NoSubscriberBehavior: {
Play: 'play',
},
StreamType: {
Raw: 'raw',
},
VoiceConnectionStatus: {
Ready: 'ready',
},
createAudioPlayer: jest.fn(() => mockAudioPlayer),
createAudioResource: jest.fn(() => mockAudioResource),
entersState: jest.fn(() => Promise.resolve(mockConnection)),
joinVoiceChannel: jest.fn(() => mockConnection),
}));
jest.mock('../src/ffmpeg', () => ({
startFfmpeg: jest.fn(() => mockFfmpegHandle),
}));
const connectionOptions: VoiceConnectionOptions = {
guildId: 'guild-id',
channelId: 'channel-id',
adapterCreator: jest.fn() as unknown as VoiceConnectionOptions['adapterCreator'],
};
const source: AudioSource = {
type: 'url',
url: 'https://example.com/audio.mp3',
};
describe('AudioManager', () => {
beforeEach(() => {
jest.clearAllMocks();
});
afterEach(() => {
jest.useRealTimers();
});
it('requires connection options before connecting', async () => {
const manager = new AudioManager({ renewIntervalMs: false });
await expect(manager.connect()).rejects.toThrow(AudioManagerConfigError);
});
it('connects and starts playback with resolved URL source', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source,
renewIntervalMs: false,
});
await manager.start();
expect(manager.state).toBe('playing');
expect(manager.isConnected).toBe(true);
expect(manager.isPlaying).toBe(true);
expect(mockConnection.subscribe).toHaveBeenCalledWith(mockAudioPlayer);
expect(startFfmpeg).toHaveBeenCalledWith('https://example.com/audio.mp3', undefined);
expect(mockAudioPlayer.play).toHaveBeenCalledWith(mockAudioResource);
});
it('resolves file sources against the current working directory', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: {
type: 'file',
path: 'audio/song.mp3',
},
renewIntervalMs: false,
});
await manager.start();
expect(startFfmpeg).toHaveBeenCalledWith(expect.stringContaining(`audio${sep}song.mp3`), undefined);
});
it('rejects invalid URL sources', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: {
type: 'url',
url: 'not a url',
},
renewIntervalMs: false,
});
await manager.connect();
await expect(manager.play()).rejects.toThrow(AudioManagerConfigError);
});
it('applies initial volume only when volume support is enabled', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source,
renewIntervalMs: false,
volume: {
enabled: true,
initialPercent: 35,
},
});
await manager.start();
expect(mockAudioResource.volume.setVolume).toHaveBeenCalledWith(0.35);
});
it('rejects volume changes when inline volume is disabled', () => {
const manager = new AudioManager({ renewIntervalMs: false });
expect(() => manager.setVolume(50)).toThrow(AudioManagerStateError);
});
it('pauses and resumes only from valid playback states', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source,
renewIntervalMs: false,
});
expect(() => manager.pause()).toThrow(AudioManagerStateError);
await manager.start();
manager.pause();
manager.resume();
expect(mockAudioPlayer.pause).toHaveBeenCalledTimes(1);
expect(mockAudioPlayer.unpause).toHaveBeenCalledTimes(1);
expect(manager.state).toBe('playing');
});
it('stops playback and voice resources idempotently', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source,
renewIntervalMs: false,
});
await manager.start();
await manager.stop();
await manager.stop();
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioResource.playStream.destroy).toHaveBeenCalledTimes(1);
expect(mockConnection.destroy).toHaveBeenCalled();
expect(manager.state).toBe('stopped');
});
it('clears existing renewal timer before reconnecting', async () => {
jest.useFakeTimers();
const manager = new AudioManager({
connection: connectionOptions,
source,
renewIntervalMs: 10_000,
});
await manager.connect();
await manager.connect();
expect(jest.getTimerCount()).toBe(1);
manager.dispose();
expect(jest.getTimerCount()).toBe(0);
});
it('prevents use after disposal', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source,
renewIntervalMs: false,
});
await manager.start();
manager.dispose();
expect(() => manager.pause()).toThrow(AudioManagerStateError);
expect(manager.state).toBe('disposed');
});
});
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": true,
"declarationMap": false,
"emitDeclarationOnly": true,
"rootDir": "./src"
},
"include": ["src/**/*.ts"]
}
+2 -2
View File
@@ -1,4 +1,4 @@
{
"extends": "./tsconfig.json",
"include": ["src/**/*.ts"]
"extends": "./tsconfig.json",
"include": ["src/**/*.ts", "tests/**/*.ts", "tsup.config.ts"]
}
+31 -18
View File
@@ -1,20 +1,33 @@
{
"compilerOptions": {
"strict": true,
"allowJs": false,
"noImplicitAny": true,
"esModuleInterop": true,
"strictNullChecks": true,
"target": "ES2022",
"moduleResolution": "Node",
"module": "CommonJS",
"declaration": true,
"isolatedModules": true,
"noEmit": true,
"outDir": "dist",
"types": ["node"],
"typeRoots": ["node_modules/@types"]
},
"include": ["src"],
"exclude": ["node_modules"]
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "Node16",
"moduleResolution": "node16",
"resolveJsonModule": true,
"types": [],
"rootDir": "./",
"outDir": "./dist",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"useUnknownInCatchVariables": true,
"skipLibCheck": true,
"noEmitOnError": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"isolatedModules": true,
"outDir": "./dist-test"
},
"include": ["src/**/*.ts", "tests/**/*.ts", "tsup.config.ts"]
}
+6 -6
View File
@@ -1,10 +1,10 @@
import { defineConfig } from 'tsup';
export default defineConfig({
format: ['cjs', 'esm'],
entry: ['./src/index.ts'],
dts: true,
shims: true,
skipNodeModulesBundle: true,
clean: true,
format: ['cjs', 'esm'],
entry: ['./src/index.ts'],
dts: false,
shims: true,
skipNodeModulesBundle: true,
clean: true,
});
-4480
View File
File diff suppressed because it is too large Load Diff