# AudioManager

### Creating an AudioManager

You can easily create an AudioManager. All you have to do is call the AudioManager class. Your code will look like this

```javascript
const discordaudio = require('discordaudio');

const audioManager = new discordaudio.AudioManager();
```

### Play a song

Playing a song is really easy. You have just created an AudioManager in the previous example. The only thing you need to do is call the play function of it. The function requires two parameters and one parameter is optional. The required parameters are the `channel` and the `stream` parameters, the optional parameter is the `options` parameter which you can use for optional options. **Note:** The `stream` parameter may also be a YouTube url.

The options parameter has the following options:

* volume: The volume of the song. Can maximum be 1 and can not be lower than 0.
* quality: The quality of the song. The quality options are:
  * 'high': Sets the quality to high **(default)**
  * 'low': Sets the quality to low
* audiotype: The audiotype of the song. This can be the following things:
  * 'arbitrary': For mp3 audio **(default)**
  * 'ogg/opus': For ogg audio
  * 'webm/opus': For webm audio
  * 'opus': For opus audio
  * 'raw': For raw audio

The play function returns a Promise. The Promise resolves a boolean. If the boolean is `true` it means that the song has been added to the queue. If the boolean is false it means that there was no queue so it's started immediately. If there pops up an error while connecting to the voice channel it will reject the Promise and returns an error.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);

audioManager.play(channel, `https://www.youtube.com/watch?v=dQw4w9WgXcQ`, {
   volume: 1,
   quality: 'high', // Unnecessary as it's by default high
   audiotype: 'arbitrary' // For YouTube it's always arbitrary, just like default so this is unnecessary as it's by default already arbitrary
}).then(queue => {
   if(queue === false) console.log(`Playing the song immediately`);
   else console.log(`The song has been added to the queue`);
}).catch(console.log);
```

### Loop a song

You can loop a song with the loop function. The function requires two parameters; the `channel` and the `loop` parameters. The `channel` parameter is the voice channel where you want to add or remove the loop and the `loop` parameter is the type of loop you want to set. You can set the type of loop with the `looptypes` property. The looptypes property has the following options:

* off: Turns the loop off.
* loop: Turns the loop on for one song.
* queueloop: Turns the loop on for the entire queue.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
audioManager.loop(channel, audioManager.looptypes.loop); // Loops the song
audioManager.loop(channel, audioManager.looptypes.queueloop); // Loops the queue
audioManager.loop(channel, audioManager.looptypes.off); // Unloops everything
```

### Stop the player in a guild

You can stop a player by using the stop function. The stop function requires the `channel` parameter. The `channel` parameter is the voice channel where you want to stop the player of.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});;

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
audioManager.stop(channel);
```

### Skip a song

You can skip a song by using the skip function. The skip function requires the `channel` parameter. The `channel` parameter is the voice channel where you want to skip a song of. The skip function returns a Promise that will be fullfilled if the song successfully got skipped, otherwhise the Promise will be rejected and returns an error.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
audioManager.skip(channel).then(() => console.log(`Skipped song!`)).catch(console.log);
```

### Pause a song

To pause a song you need to use the `pause` function. The function requires the `channel` parameter which is the VoiceChannel where the song is playing that you want to pause.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
audioManager.pause(channel);
```

### Resume a paused song

To resume a song you need to use the `resume` function. The function requires the `channel` parameter which is the VoiceChannel where the song is paused that you want to resume.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
audioManager.resume(channel);
```

### Queue

You can get the queue by using the queue function. The queue function returns an array with JSON object in it. The JSON properties that will return are:

* title: The title of the song. (Can only be checked with YouTube songs else it will return a property of null.)
* url: The url of the song.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
const queue = audioManager.queue(channel).reduce((string, song, indexOf) => {
    if(song.title) string += `**[${indexOf + 1}]** ${song.title}`;
    else string += `**[${indexOf + 1}]** ${song.url}`;
    return string;
}, `Songs:`);
console.log(queue);
```

### Delete a song of the queue

You can delete a song of the queue by using the deletequeue function. The deletequeue function requires the `channel` and the `stream` parameter. The `channel` parameter is the voice channel where you want to delete a song of the queue. The `stream` parameter is the stream which you want to delete of the queue. The deletequeue function will return a Promise which will be fullfilled if the song successfully got deleted. There will only become an error if the stream is not in the queue.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
await audioManager.deletequeue(channel, `https://www.youtube.com/watch?v=dQw4w9WgXcQ`);
```

### Clear the queue

You can easily clear the queue by using the clearqueue function. This function will clear the whole queue. If there is still playing a song, when you're using the clearqueue function, the song will play until it's ended. You can also use the skip function if you want to stop the player. The clearqueue function requires the `channel` parameter. The channel parameter is the voice channel where you want to clear the queue.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
audioManager.clearqueue(channel);
```

### Destroy all players

You can destroy all the players that are playing by using the destroy function. By using this function all the players that are being played will be destroyed and the bot will leave all the voice channels. To destroy one audio player you can use the [stop function](https://zyno-studio.gitbook.io/discord-audio/classes/broken-reference).

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
audioManager.destroy();
```

### Event listeners

The AudioManager class provides 7 events:

* play: Once a song starts playing.
* queue\_add: Once a song gets added to the queue.
* queue\_remove: Once a song gets removed from the queue.
* end: Once all the songs in the queue ended.
* error: Once there pops up an error.
* destroy: Once all players get destroyed.
* connection\_destroy: If one player gets destroyed.

```javascript
const discordaudio = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.intents.FLAGS.GUILD_VOICE_STATES]});

const audioManager = new discordaudio.AudioManager();

const channel = client.channels.cache.get(`0123456789`);
...
audioManager.on('play', (channel, stream) => console.log(`Playing ${stream} i
n ${channel.name}`));

audioManager.on('queue_add', (channel, stream ) => console.log(`Added ${stream} in ${channel.name} to the queue`);

audioManager.on('queue_remove', (channel, stream) => console.log(`Removed ${stream} in ${channel.name} from the queue`));

audioManager.on('end', channel => console.log(`Queue ended in ${channel.name}`));

audioManager.on('error', error => console.log(error));

audioManager.on('destroy', () => console.log(`All players got destroyed`));

audioManager.on('connection_destroy', channel => console.log(`The player of ${channel.name} got destroyed`));
```

### Example

```javascript
const {AudioManager} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS, discord.Intents.FLAGS.GUILD_MESSAGES, discord.Intents.FLAGS.GUILD_VOICE_STATES]});

const config = {
    token: 'Your-Secret-Token',
    prefix: '-'
};

const connections = new Map();

const audioManager = new AudioManager();

client.once('ready', () => console.log(`${client.user.username} is online!`));

client.on('messageCreate', message => {
    if(message.author.bot || message.channel.type === `DM`) return;
    
    if(!message.content.startsWith(config.prefix)) return;
    
    let args = message.content.substring(config.prefix.length).split(" ");
    
    const vc = connections.get(message.guild.me.voice.channel?.id);
    
    switch(args[0].toLowerCase()){
        case 'play':
            if(!message.member.voice.channel && !message.guild.me.voice.channel) return message.channel.send({content: `Please join a voice channel in order to play a song!`});
            if(!args[1]) return message.channel.send({content: `Please provide a song`});
            const uvc = message.guild.me.voice.channel || message.member.voice.channel;
            audioManager.play(uvc, args[1], {
                quality: 'high',
                audiotype: 'arbitrary',
                volume: 10
            }).then(queue => {
                connections.set(uvc.id, uvc);
                if(queue === false) message.channel.send({content: `Your song is now playing!`});
                else message.channel.send({content: `Your song has been added to the queue!`});
            }).catch(err => {
                console.log(err);
                message.channel.send({content: `There was an error while trying to connect to the voice channel!`});
            });
            break;
        case 'skip':
            if(!vc) return message.channel.send({content: `There is currently nothing playing!`});
            audioManager.skip(vc).then(() => message.channel.send({content: `Successfully skipped the song!`})).catch(err => {
                console.log(err);
                message.channel.send({content: `There was an error while skipping the song!`});
            });
            break;
        case 'stop':
            if(!vc) return message.channel.send({content: `There is currently nothing playing!`});
            audioManager.stop(vc);
            message.channel.send({content: `Player successfully stopped!`});            
            break;
        case 'queue':
            if(!vc) return message.channel.send({content: `There is currently nothing playing!`});
            const queue = audioManager.queue(vc).reduce((text, song, index) => {
                if(song.title) text += `**[${index + 1}]** ${song.title}`;
                else text += `**[${index + 1}]** ${song.url}`;
                return text;
            }, `__**QUEUE**__`);
            const queueEmbed = new discord.MessageEmbed()
            .setColor(`BLURPLE`)
            .setTitle(`Queue`)
            .setDescription(queue);
            message.channel.send({embeds: [queueEmbed]});
            break;
        case 'volume':
            if(!vc) return message.channel.send({content: `There is currently nothing playing!`});
            if(!args[1]) return message.channel.send({content: `Please provide the volume`});
            if(Number(args[1] < 1 || Number(args[1]) > 10)) return message.channel.send({content: `Please provide a volume between 1-10`});
            audioManager.volume(vc, Number(args[1]));
            break;
    }
});

client.login(config.token);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zyno-studio.gitbook.io/discord-audio/classes/audiomanager.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
