Compare commits
45
Commits
v0.6
..
v1.0.1431918
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51d738a442 | ||
|
|
db7de9c04d | ||
|
|
eaf86f948b | ||
|
|
d4f92e1eac | ||
|
|
9eace0838b | ||
|
|
5cc7127a5a | ||
|
|
7923b917d8 | ||
|
|
78cbf3f233 | ||
|
|
4cc9774ff5 | ||
|
|
6962d87f24 | ||
|
|
966db49e37 | ||
|
|
707822e43d | ||
|
|
29f51c5ff0 | ||
|
|
ee676212ab | ||
|
|
5496514dab | ||
|
|
1e08cddc61 | ||
|
|
d07efd73a5 | ||
|
|
4447437fd2 | ||
|
|
199f9f84c5 | ||
|
|
78bc4b4f24 | ||
|
|
b0dc3ba52b | ||
|
|
431c720162 | ||
|
|
309eb75716 | ||
|
|
ba9709ddd1 | ||
|
|
bac8b41cb9 | ||
|
|
ecc3189054 | ||
|
|
96ee35c1e4 | ||
|
|
f712ea73d7 | ||
|
|
21d8894629 | ||
|
|
fe79bfae5e | ||
|
|
0b0ae23c62 | ||
|
|
0a0bb40020 | ||
|
|
36bfd035e9 | ||
|
|
20438ee041 | ||
|
|
3bb0784850 | ||
|
|
7412182b02 | ||
|
|
9ed38deac9 | ||
|
|
f9aed907e6 | ||
|
|
af7a7e266f | ||
|
|
a5edc62b6a | ||
|
|
9abd7c1628 | ||
|
|
ba6a1e3cc7 | ||
|
|
4d3351d81e | ||
|
|
94328ef054 | ||
|
|
520dee397f |
@@ -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
|
||||||
@@ -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
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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'
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
name: Build Rollout
|
name: Release and Deploy Build
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
id-token: write
|
contents: write
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -14,26 +13,75 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout Repository
|
- name: Checkout Repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: use NodeJS v22.16.0
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
with:
|
||||||
node-version: '22.16.0'
|
fetch-depth: 0
|
||||||
registry-url: 'https://registry.npmjs.org'
|
fetch-tags: true
|
||||||
always-auth: true
|
|
||||||
|
|
||||||
- name: Create .npmrc
|
- name: Use NodeJS v24.14.0
|
||||||
run: echo "//registry.npmjs.org/:_authToken=\${NPM_TOKEN}" > ~/.npmrc
|
uses: actions/setup-node@v6
|
||||||
env:
|
with:
|
||||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
node-version: '24.14.0'
|
||||||
|
registry-url: 'https://registry.npmjs.org'
|
||||||
|
package-manager-cache: false
|
||||||
|
|
||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
run: npm install
|
run: npm ci
|
||||||
|
|
||||||
- name: run Rollout Build
|
- name: Set Release Version
|
||||||
run: npm run rolloutBuild
|
id: version
|
||||||
|
run: npm run release:version
|
||||||
|
|
||||||
|
- name: Export Release Version
|
||||||
|
id: release_version
|
||||||
|
run: |
|
||||||
|
package_version="$(node -p "require('./package.json').version")"
|
||||||
|
echo "tag=${package_version}" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Run Build
|
||||||
|
run: npm run build
|
||||||
|
|
||||||
- name: Publish Library
|
- name: Publish Library
|
||||||
run: npm publish
|
run: npm publish --access public
|
||||||
env:
|
env:
|
||||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
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
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
name: Build Validation
|
name: Build Validation
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
pull_request:
|
pull_request:
|
||||||
types: [opened, synchronize, reopened]
|
types: [opened, synchronize, reopened]
|
||||||
|
|
||||||
@@ -11,13 +15,16 @@ jobs:
|
|||||||
- name: Checkout Repository
|
- name: Checkout Repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: use NodeJS v22.16.0
|
- name: use NodeJS v24.14.0
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '22.16.0'
|
node-version: '24.14.0'
|
||||||
|
|
||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
run: npm install
|
run: npm ci
|
||||||
|
|
||||||
- name: run Rollout Build
|
- name: Run Checks
|
||||||
run: npm run rolloutBuild
|
run: npm run check
|
||||||
|
|
||||||
|
- name: Run Build
|
||||||
|
run: npm run build
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
npm run check || exit 1
|
||||||
+24
-5
@@ -1,10 +1,29 @@
|
|||||||
.idea
|
|
||||||
.git
|
|
||||||
.github
|
.github
|
||||||
|
.git
|
||||||
|
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
|
||||||
|
dist
|
||||||
|
node_modules
|
||||||
|
|
||||||
|
.husky
|
||||||
|
src
|
||||||
|
set-version.js
|
||||||
|
|
||||||
|
README.md
|
||||||
|
SECURITY.md
|
||||||
|
CODEOWNERS
|
||||||
|
|
||||||
.gitignore
|
.gitignore
|
||||||
.npmignore
|
.npmignore
|
||||||
node_modules
|
.prettierignore
|
||||||
src
|
.prettierrc
|
||||||
README.md
|
.gitattributes
|
||||||
|
|
||||||
tsconfig.json
|
tsconfig.json
|
||||||
|
tsconfig.eslint.json
|
||||||
tsup.config.ts
|
tsup.config.ts
|
||||||
|
eslint.config.js
|
||||||
|
eslint.config.typeaware.cjs
|
||||||
|
package-lock.json
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
.git
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
+13
@@ -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"
|
||||||
|
}
|
||||||
@@ -1,87 +1,315 @@
|
|||||||
# Discord Audio Stream
|
# Discord Audio Stream
|
||||||
|
|
||||||
[](http://npmjs.org/package/discord-audio-stream)
|
[](http://npmjs.org/package/discord-audio-stream)
|
||||||

|

|
||||||

|

|
||||||
|
|
||||||
**This module is designed to work with [discord.js/voice](https://www.npmjs.com/package/@discordjs/voice) v0.18. This
|
> **Designed for 24/7 Discord audio playback.**
|
||||||
package doesn't support older
|
> `discord-audio-stream` is a small TypeScript library for managed Discord voice playback through
|
||||||
versions!**
|
> `@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
|
## 👋 Support
|
||||||
|
|
||||||
Please create an [issue](https://github.com/FrauJulian/DiscordAudioStreamNPM/issues) on github or write [
|
Please create an [issue](https://github.com/FrauJulian/Discord-Audio-Stream/issues) on GitHub or contact
|
||||||
`fraujulian`](https://discord.com/users/860206216893693973) on discord!
|
[`fraujulian`](https://discord.com/users/860206216893693973) on Discord.
|
||||||
|
|
||||||
## 📝 Usage
|
## 📝 Usage
|
||||||
|
|
||||||
### Install package
|
### Installation
|
||||||
|
|
||||||
|
**Node.js `22.12.0` or newer is required.**
|
||||||
|
|
||||||
|
Install the library and the required voice packages:
|
||||||
|
|
||||||
```bash
|
```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
|
```bash
|
||||||
let audioManager = new AudioManager();
|
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
|
```bash
|
||||||
let audioManager = new AudioManager({
|
npm install ffmpeg-static
|
||||||
VoiceChannelId: 0, //voice channel id where to play music
|
```
|
||||||
GuildId: 0, //guild id
|
|
||||||
VoiceAdapter: 0 //guild VoiceAdapter
|
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,
|
||||||
},
|
},
|
||||||
{
|
source: {
|
||||||
ResourceType: "", //resource type like link or file
|
type: 'url',
|
||||||
Resource: "" //auto play link or file name
|
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 |
|
await manager.start();
|
||||||
|-------------------|------------------------------|-------------------------------------------------|
|
```
|
||||||
| `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. |
|
|
||||||
|
|
||||||
#### Methods
|
Relative file paths are resolved from `process.cwd()`. URL sources are validated before playback starts.
|
||||||
|
|
||||||
| Callable with | Parameters | Return type | Description |
|
## ⚙️ API
|
||||||
|--------------------------------|--------------------------------------------------------------------------------------------------------|-------------|--------------------------------------------------------------------|
|
|
||||||
| `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. |
|
|
||||||
|
|
||||||
##### Types History
|
### Constructor
|
||||||
|
|
||||||
- [**VoiceConnection** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/VoiceConnection.ts#L166)
|
```ts
|
||||||
- [**AudioPlayer** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioPlayer.ts#L155)
|
type AudioManagerOptions = {
|
||||||
- [**AudioResource** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioResource.ts#L44)
|
ffmpeg?: {
|
||||||
- [**VoiceConnectionDataModel**](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceConnectionDataModel.d.ts#L3) (custom type)
|
mode?: 'native' | 'static';
|
||||||
- [**VoiceAudioDataModel**](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceAudioDataModel.d.ts#L1) (custom type)
|
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?
|
## 🤝 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)!
|
||||||
|
|
||||||
### Greetings from Austria! ⛰️
|
|
||||||
|
|||||||
+18
@@ -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.
|
||||||
@@ -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;
|
||||||
@@ -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];
|
||||||
@@ -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',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
Generated
+7937
-1289
File diff suppressed because it is too large
Load Diff
+64
-31
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "discord-audio-stream",
|
"name": "discord-audio-stream",
|
||||||
"version": "0.6.12",
|
"version": "1.0.DDDhhmm",
|
||||||
"license": "LGPL-2.1-only",
|
"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": {
|
"exports": {
|
||||||
".": {
|
".": {
|
||||||
"require": {
|
"require": {
|
||||||
@@ -25,52 +25,85 @@
|
|||||||
"lib": "src"
|
"lib": "src"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"updateDependencies": "npx npm-check-updates --upgrade && npm install && echo SUCCEED UPDATE",
|
"update:dependencies": "npx npm-check-updates --upgrade",
|
||||||
"cleanSolution": "del-cli dist && echo SUCCEED CLEAN",
|
"release:version": "node set-version.js",
|
||||||
"updateVersion": "npm version patch --no-git-tag-version && echo SUCCEED UPDATE VERSION",
|
"lint": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs",
|
||||||
"buildPackage": "tsup && echo SUCCEED BUILD && npm run updateVersion",
|
"lint:fix": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs --fix",
|
||||||
"rolloutBuild": "npm run updateDependencies && npm run cleanSolution && tsup"
|
"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",
|
"bugs": "https://github.com/FrauJulian/Discord-Audio-Stream/issues",
|
||||||
"funding": "https://ko-fi.com/FrauJulian",
|
"funding": "https://ko-fi.com/FrauJulian",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"discordjs",
|
"discordjs",
|
||||||
"discord.js",
|
"discordjs/voice",
|
||||||
"discord",
|
"music",
|
||||||
"audio",
|
|
||||||
"voice",
|
"voice",
|
||||||
"stream"
|
"audio",
|
||||||
|
"24/7"
|
||||||
],
|
],
|
||||||
"contributors": [
|
"contributors": [
|
||||||
{
|
"FrauJulian - Lechner Julian <fraujulian@lechner.top>"
|
||||||
"name": "Lechner Julian",
|
|
||||||
"nickname": "FrauJulian",
|
|
||||||
"email": "office@lechner-systems.at",
|
|
||||||
"website": "https://lechner-systems.at/"
|
|
||||||
}
|
|
||||||
],
|
],
|
||||||
"dependencies": {
|
"lint-staged": {
|
||||||
"@noble/ciphers": "^1.3.0",
|
"*.{ts,tsx,js,cjs,mjs}": [
|
||||||
"@stablelib/xchacha20poly1305": "^2.0.1",
|
"eslint --fix",
|
||||||
"sodium-native": "^5.0.6"
|
"prettier --write"
|
||||||
|
],
|
||||||
|
"*.{json,md,yml,yaml}": [
|
||||||
|
"prettier --write"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@jest/globals": "^30.4.1",
|
||||||
"@types/ejs": "^3.1.5",
|
"@types/ejs": "^3.1.5",
|
||||||
"@types/node": "^24.1.0",
|
"@types/node": "^25.9.1",
|
||||||
"del-cli": "^6.0.0",
|
"@typescript-eslint/eslint-plugin": "^8.59.4",
|
||||||
"npm-check-updates": "^18.0.2",
|
"@typescript-eslint/parser": "^8.59.4",
|
||||||
"tsup": "^8.5.0",
|
"del-cli": "^7.0.0",
|
||||||
"typescript": "^5.8.3"
|
"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": {
|
"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",
|
"libsodium-wrappers": "^0.7.15",
|
||||||
"opusscript": "^0.1.1",
|
"opusscript": "^0.0.8",
|
||||||
"ffmpeg-static": "^5.2.0"
|
"prism-media": "^1.3.5"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"ffmpeg-static": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"libsodium-wrappers": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=22.12.0"
|
||||||
},
|
},
|
||||||
"private": false,
|
"private": false,
|
||||||
"publishConfig": {
|
"publishConfig": {
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -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);
|
||||||
@@ -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.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
@@ -1,3 +1,11 @@
|
|||||||
export {default as AudioManager} from './audioManager';
|
export { default as AudioManager } from './audio-manager';
|
||||||
export type {VoiceConnectionDataModel} from './types/VoiceConnectionDataModel';
|
export { AudioManagerConfigError, AudioManagerError, AudioManagerStateError, FfmpegProcessError } from './errors';
|
||||||
export type {VoiceAudioDataModel} from './types/VoiceAudioDataModel';
|
export type {
|
||||||
|
AudioManagerOptions,
|
||||||
|
AudioSource,
|
||||||
|
FfmpegMode,
|
||||||
|
FfmpegOptions,
|
||||||
|
PlaybackState,
|
||||||
|
VoiceConnectionOptions,
|
||||||
|
VolumeOptions,
|
||||||
|
} from './types';
|
||||||
|
|||||||
+178
@@ -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;
|
||||||
|
};
|
||||||
Vendored
-12
@@ -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
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"declaration": true,
|
||||||
|
"declarationMap": false,
|
||||||
|
"emitDeclarationOnly": true,
|
||||||
|
"rootDir": "./src"
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"include": ["src/**/*.ts", "tests/**/*.ts", "tsup.config.ts"]
|
||||||
|
}
|
||||||
+28
-23
@@ -1,28 +1,33 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"strict": true,
|
|
||||||
"allowJs": false,
|
|
||||||
"noImplicitAny": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"strictNullChecks": true,
|
|
||||||
"target": "ES2022",
|
"target": "ES2022",
|
||||||
"moduleResolution": "Node",
|
"lib": ["ES2022"],
|
||||||
"module": "CommonJS",
|
"module": "Node16",
|
||||||
"declaration": true,
|
"moduleResolution": "node16",
|
||||||
"isolatedModules": true,
|
"resolveJsonModule": true,
|
||||||
"noEmit": true,
|
"types": [],
|
||||||
"outDir": "dist",
|
"rootDir": "./",
|
||||||
"types": [
|
"outDir": "./dist",
|
||||||
"node"
|
"esModuleInterop": true,
|
||||||
],
|
"allowSyntheticDefaultImports": true,
|
||||||
"typeRoots": [
|
"forceConsistentCasingInFileNames": true,
|
||||||
"node_modules/@types"
|
"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": [
|
"include": ["src"],
|
||||||
"src"
|
"exclude": ["node_modules", "dist"]
|
||||||
],
|
|
||||||
"exclude": [
|
|
||||||
"node_modules"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"isolatedModules": true,
|
||||||
|
"outDir": "./dist-test"
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "tests/**/*.ts", "tsup.config.ts"]
|
||||||
|
}
|
||||||
+4
-4
@@ -1,9 +1,9 @@
|
|||||||
import {defineConfig} from "tsup";
|
import { defineConfig } from 'tsup';
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
format: ["cjs", "esm"],
|
format: ['cjs', 'esm'],
|
||||||
entry: ["./src/index.ts"],
|
entry: ['./src/index.ts'],
|
||||||
dts: true,
|
dts: false,
|
||||||
shims: true,
|
shims: true,
|
||||||
skipNodeModulesBundle: true,
|
skipNodeModulesBundle: true,
|
||||||
clean: true,
|
clean: true,
|
||||||
|
|||||||
Reference in New Issue
Block a user