45 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
fraujulianandGitHub fe79bfae5e Merge pull request #18 from FrauJulian/fraujulian
Updated types and dependencies
2025-10-10 18:12:12 +02:00
Lechner Julian - FrauJulian 0b0ae23c62 Updated package.json 2025-10-10 18:08:42 +02:00
Lechner Julian - FrauJulian 0a0bb40020 Updated README.md; Changed scripts in ci; 2025-10-10 18:05:20 +02:00
Lechner Julian - FrauJulian 36bfd035e9 Updated README.md 2025-10-10 18:01:10 +02:00
Lechner Julian - FrauJulian 20438ee041 Updated README.md 2025-10-10 17:58:19 +02:00
Lechner Julian - FrauJulian 3bb0784850 Merge remote-tracking branch 'origin/fraujulian' into fraujulian
# Conflicts:
#	package.json
2025-10-10 17:55:17 +02:00
Lechner Julian - FrauJulian 7412182b02 Added yarn, bun and pnpm config; Added eslint and prettier; Refactored Type import; Updated Version; 2025-10-10 17:52:56 +02:00
fraujulianandGitHub 9ed38deac9 Bump version from 0.6.13 to 0.6.14 2025-10-03 15:38:08 +02:00
fraujulianandGitHub f9aed907e6 Merge pull request #17 from FrauJulian/fraujulian
Fixed AudioTimeout (hopefully); Refactored; Updated Dependencies;
2025-10-03 15:37:21 +02:00
Lechner Julian - FrauJulian af7a7e266f Fixed AudioTimeout (hopefully); Refactored; Updated Dependencies; 2025-10-03 15:33:49 +02:00
fraujulianandGitHub a5edc62b6a Merge pull request #15 from FrauJulian/13_unit_tests_and_fix_memory_leak
13 unit tests and fix memory leak
2025-08-02 17:58:35 +02:00
Lechner Julian - FrauJulian 9abd7c1628 removed ,; 2025-08-02 17:57:16 +02:00
Lechner Julian - FrauJulian ba6a1e3cc7 update version; 2025-08-02 17:55:58 +02:00
Lechner Julian - FrauJulian 4d3351d81e fixed memory leak; removed unit tests; 2025-08-02 17:55:25 +02:00
Julian lechner 94328ef054 added unit test script; added dev dependencies; 2025-07-31 12:39:36 +02:00
fraujulian 520dee397f Add comprehensive jest unit tests 2025-07-31 09:30:21 +02:00
36 changed files with 10129 additions and 2037 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.16.0
uses: actions/setup-node@v4
with:
node-version: '22.16.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 rolloutBuild
- 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 rolloutBuild
- name: Run Checks
run: npm run check
- name: Run Build
run: npm run build
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env sh
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
+13
View File
@@ -0,0 +1,13 @@
{
"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
+282 -54
View File
@@ -1,87 +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 package
### Installation
**Node.js `22.12.0` or newer is required.**
Install the library and the required voice packages:
```bash
npm install discord-audio-stream opusscript @discordjs/voice ffmpeg-static sodium-native
npm install discord-audio-stream @discordjs/voice prism-media @snazzah/davey opusscript
```
### Create Instance
`libsodium-wrappers` is optional. Install it only when your runtime does not support `aes-256-gcm`:
```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
```bash
npm install ffmpeg-static
```
If ffmpeg is already available on the host PATH, use `ffmpeg.mode: 'native'`.
### AudioManager Example
```ts
import { AudioManager } from 'discord-audio-stream';
const manager = new AudioManager({
connection: {
guildId: guild.id,
channelId: voiceChannel.id,
adapterCreator: guild.voiceAdapterCreator,
},
{
ResourceType: "", //resource type like link or file
Resource: "" //auto play link or file name
});
source: {
type: 'url',
url: 'https://example.com/live-stream.mp3',
},
ffmpeg: {
mode: 'native',
},
renewIntervalMs: 5_400_000,
});
await manager.start();
```
### Properties of the AudioManager
For a file source:
#### Properties
```ts
manager.setSource({
type: 'file',
path: 'audio/intro.mp3',
});
| 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. |
await manager.start();
```
#### Methods
Relative file paths are resolved from `process.cwd()`. URL sources are validated before playback starts.
| Callable with | Parameters | Return type | Description |
|--------------------------------|--------------------------------------------------------------------------------------------------------|-------------|--------------------------------------------------------------------|
| `OverrideOptions` | `connectionData` (type of **VoiceConnectionDataModel**), `audioData` (type of **VoiceAudioDataModel**) | void | Method to override global variables, connectionData and audioData. |
| `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. |
| `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. |
## ⚙️ API
##### Types History
### Constructor
- [**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**](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceConnectionDataModel.d.ts#L3) (custom type)
- [**VoiceAudioDataModel**](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceAudioDataModel.d.ts#L1) (custom type)
```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;
};
};
```
## 📋 Credits:
### Defaults
~ [**FrauJulian**](https://fraujulian.xyz/).
| 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)!
### Greetings from Austria! ⛰️
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.
+91
View File
@@ -0,0 +1,91 @@
/** @type {import('eslint').Linter.FlatConfig[]} */
const config = [
{
ignores: ['dist/', 'node_modules/'],
},
{
files: ['**/*.{ts,tsx,js,cjs,mjs}'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
parser: require('@typescript-eslint/parser'),
parserOptions: {
ecmaFeatures: {},
},
},
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'),
},
rules: {
/* Base */
'no-debugger': 'warn',
/* 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',
/* 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}',
],
},
],
/* 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 }],
},
settings: {
'import/resolver': {
typescript: {
alwaysTryTypes: true,
},
node: true,
},
},
},
{
files: ['**/*.{js,cjs}'],
languageOptions: {
sourceType: 'script',
},
rules: {
'n/global-require': 'off',
},
},
];
module.exports = config;
+25
View File
@@ -0,0 +1,25 @@
/** @type {import('eslint').Linter.FlatConfig[]} */
const base = require('./eslint.config.cjs');
const typeAwareLayer = {
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',
},
};
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',
},
],
},
};
+7932 -1284
View File
File diff suppressed because it is too large Load Diff
+64 -31
View File
@@ -1,8 +1,8 @@
{
"name": "discord-audio-stream",
"version": "0.6.12",
"version": "1.0.DDDhhmm",
"license": "LGPL-2.1-only",
"description": "NodeJS library to make stream any audio on discord easier.",
"description": "A small Discord voice audio streaming library with managed ffmpeg playback.",
"exports": {
".": {
"require": {
@@ -25,52 +25,85 @@
"lib": "src"
},
"scripts": {
"updateDependencies": "npx npm-check-updates --upgrade && npm install && echo SUCCEED UPDATE",
"cleanSolution": "del-cli dist && echo SUCCEED CLEAN",
"updateVersion": "npm version patch --no-git-tag-version && echo SUCCEED UPDATE VERSION",
"buildPackage": "tsup && echo SUCCEED BUILD && npm run updateVersion",
"rolloutBuild": "npm run updateDependencies && npm run cleanSolution && tsup"
"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"
},
"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",
"discord",
"audio",
"discordjs/voice",
"music",
"voice",
"stream"
"audio",
"24/7"
],
"contributors": [
{
"name": "Lechner Julian",
"nickname": "FrauJulian",
"email": "office@lechner-systems.at",
"website": "https://lechner-systems.at/"
}
"FrauJulian - Lechner Julian <fraujulian@lechner.top>"
],
"dependencies": {
"@noble/ciphers": "^1.3.0",
"@stablelib/xchacha20poly1305": "^2.0.1",
"sodium-native": "^5.0.6"
"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": "^24.1.0",
"del-cli": "^6.0.0",
"npm-check-updates": "^18.0.2",
"tsup": "^8.5.0",
"typescript": "^5.8.3"
"@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.18.0",
"@discordjs/voice": "^0.19.0",
"@snazzah/davey": "^0.1.8",
"ffmpeg-static": "^5.2.0",
"libsodium-wrappers": "^0.7.15",
"opusscript": "^0.1.1",
"ffmpeg-static": "^5.2.0"
"opusscript": "^0.0.8",
"prism-media": "^1.3.5"
},
"peerDependenciesMeta": {
"ffmpeg-static": {
"optional": true
},
"libsodium-wrappers": {
"optional": true
}
},
"engines": {
"node": ">=18"
"node": ">=22.12.0"
},
"private": false,
"publishConfig": {
+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);
+257
View File
@@ -0,0 +1,257 @@
import type { AudioPlayer, AudioResource, VoiceConnection } from '@discordjs/voice';
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 {
private readonly audioPlayer: AudioPlayer;
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'>;
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,
},
});
}
public get state(): PlaybackState {
return this.playbackState;
}
public get isPlaying(): boolean {
return this.playbackState === 'playing';
}
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.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);
await entersState(this.connection, VoiceConnectionStatus.Ready, this.options.connectTimeoutMs);
this.playbackState = 'ready';
this.scheduleRenewal();
}
public async play(source?: AudioSource): Promise<void> {
this.assertNotDisposed();
if (source) {
this.setSource(source);
}
if (!this.connection) {
throw new AudioManagerStateError('A voice connection is required before audio can be played.');
}
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,
});
if (this.options.volume?.enabled === true && this.options.volume.initialPercent !== undefined) {
this.setVolume(this.options.volume.initialPercent);
}
this.audioPlayer.play(this.resource);
this.playbackState = 'playing';
}
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.');
}
}
}
-137
View File
@@ -1,137 +0,0 @@
import {
AudioPlayer,
AudioResource,
createAudioPlayer,
createAudioResource,
joinVoiceChannel,
VoiceConnection
} from "@discordjs/voice";
import {join} from "node:path";
import {VoiceConnectionDataModel} from "./types/VoiceConnectionDataModel";
import {VoiceAudioDataModel} from "./types/VoiceAudioDataModel";
export default class AudioManager {
public VoiceConnection: VoiceConnection | null = null;
public AudioPlayer: AudioPlayer | null = null;
public AudioResource: AudioResource | null = null;
protected IsActive: boolean = false;
protected IsAudioPlaying: boolean = false;
protected ConnectionData: VoiceConnectionDataModel | null;
protected AudioData: VoiceAudioDataModel | null;
constructor(connectionData: VoiceConnectionDataModel | null = null, audioData: VoiceAudioDataModel | null = null) {
this.ConnectionData = connectionData;
this.AudioData = audioData;
}
public OverrideOptions(connectionData: VoiceConnectionDataModel | null = null, audioData: VoiceAudioDataModel | null = null): void {
this.ConnectionData = connectionData;
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;
}
}
this.VoiceConnection = joinVoiceChannel({
channelId: this.ConnectionData!.VoiceChannelId.toString(),
guildId: this.ConnectionData!.GuildId.toString(),
adapterCreator: this.ConnectionData!.VoiceAdapter
});
setTimeout((): void => {
this.RenewConnectionAndAudio();
}, 5400000);
}
public PlayAudioOnConnection(): void {
this.CheckIfNull(this.AudioData);
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.");
}
this.AudioPlayer = createAudioPlayer();
this.AudioPlayer.play(this.AudioResource);
this.VoiceConnection!.subscribe(this.AudioPlayer!);
this.IsAudioPlaying = true;
}
public StopAudioOnConnection(): void {
if (this.IsAudioPlaying) {
this.DestroyConnection(false)
this.CreateConnection();
} else {
throw new Error("Audio is not playing.");
}
}
public PauseAudio(): void {
this.CheckIfNull(this.AudioPlayer);
this.AudioPlayer!.pause();
}
public ResumeAudio(): void {
this.CheckIfNull(this.AudioPlayer);
this.AudioPlayer!.unpause();
}
public CreateConnectionAndPlayAudio(): void {
this.CreateConnection();
this.PlayAudioOnConnection();
}
public DestroyConnection(resetValidationParameters: boolean = true): void {
this.CheckIfNull(this.VoiceConnection);
this.VoiceConnection!.destroy();
if (resetValidationParameters) {
this.IsActive = false;
this.IsAudioPlaying = false;
}
}
public SetMaxListeners(maxListeners: number): void {
this.CheckIfNull(this.VoiceConnection);
this.VoiceConnection!.setMaxListeners(maxListeners);
}
public SetVolume(volumeInPercent: number): void {
if (volumeInPercent < 0 || volumeInPercent > 100) throw new Error("Volume must be between 0 and 100.");
this.AudioResource!.volume!.setVolume(volumeInPercent / 100);
}
private RenewConnectionAndAudio(): void {
this.DestroyConnection(false);
if (this.IsActive) {
this.CreateConnection(true);
if (this.IsAudioPlaying) {
this.PlayAudioOnConnection();
}
}
}
private CheckIfNull<T>(value: T | null): boolean {
if (value === null) {
throw new Error(`${value} cannot be null in this case.`);
}
return true;
}
}
+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();
}
+11 -3
View File
@@ -1,3 +1,11 @@
export {default as AudioManager} from './audioManager';
export type {VoiceConnectionDataModel} from './types/VoiceConnectionDataModel';
export type {VoiceAudioDataModel} from './types/VoiceAudioDataModel';
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;
};
-12
View File
@@ -1,12 +0,0 @@
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;
}
-19
View File
@@ -1,19 +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;
}
+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"]
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"include": ["src/**/*.ts", "tests/**/*.ts", "tsup.config.ts"]
}
+31 -26
View File
@@ -1,28 +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"]
}
+4 -4
View File
@@ -1,9 +1,9 @@
import {defineConfig} from "tsup";
import { defineConfig } from 'tsup';
export default defineConfig({
format: ["cjs", "esm"],
entry: ["./src/index.ts"],
dts: true,
format: ['cjs', 'esm'],
entry: ['./src/index.ts'],
dts: false,
shims: true,
skipNodeModulesBundle: true,
clean: true,