net.dv8tion.jda.api.managers.AudioManager Java Examples

The following examples show how to use net.dv8tion.jda.api.managers.AudioManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSocketClient.java    From JDA with Apache License 2.0 6 votes vote down vote up
protected void updateAudioManagerReferences()
{
    AbstractCacheView<AudioManager> managerView = api.getAudioManagersView();
    try (UnlockHook hook = managerView.writeLock())
    {
        final TLongObjectMap<AudioManager> managerMap = managerView.getMap();
        if (managerMap.size() > 0)
            LOG.trace("Updating AudioManager references");

        for (TLongObjectIterator<AudioManager> it = managerMap.iterator(); it.hasNext(); )
        {
            it.advance();
            final long guildId = it.key();
            final AudioManagerImpl mng = (AudioManagerImpl) it.value();

            GuildImpl guild = (GuildImpl) api.getGuildById(guildId);
            if (guild == null)
            {
                //We no longer have access to the guild that this audio manager was for. Set the value to null.
                queuedAudioConnections.remove(guildId);
                mng.closeAudioConnection(ConnectionStatus.DISCONNECTED_REMOVED_DURING_RECONNECT);
                it.remove();
            }
        }
    }
}
 
Example #2
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public AudioManager getAudioManager()
{
    if (!getJDA().isIntent(GatewayIntent.GUILD_VOICE_STATES))
        throw new IllegalStateException("Cannot use audio features with disabled GUILD_VOICE_STATES intent!");
    final AbstractCacheView<AudioManager> managerMap = getJDA().getAudioManagersView();
    AudioManager mng = managerMap.get(id);
    if (mng == null)
    {
        // No previous manager found -> create one
        try (UnlockHook hook = managerMap.writeLock())
        {
            GuildImpl cachedGuild = (GuildImpl) getJDA().getGuildById(id);
            if (cachedGuild == null)
                throw new IllegalStateException("Cannot get an AudioManager instance on an uncached Guild");
            mng = managerMap.get(id);
            if (mng == null)
            {
                mng = new AudioManagerImpl(cachedGuild);
                managerMap.getMap().put(id, mng);
            }
        }
    }
    return mng;
}
 
Example #3
Source File: AudioEchoExample.java    From JDA with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to requested channel and start echo handler
 *
 * @param channel
 *        The channel to connect to
 */
private void connectTo(VoiceChannel channel)
{
    Guild guild = channel.getGuild();
    // Get an audio manager for this guild, this will be created upon first use for each guild
    AudioManager audioManager = guild.getAudioManager();
    // Create our Send/Receive handler for the audio connection
    EchoHandler handler = new EchoHandler();

    // The order of the following instructions does not matter!

    // Set the sending handler to our echo system
    audioManager.setSendingHandler(handler);
    // Set the receiving handler to the same echo system, otherwise we can't echo anything
    audioManager.setReceivingHandler(handler);
    // Connect to the voice channel
    audioManager.openAudioConnection(channel);
}
 
Example #4
Source File: DefaultAudioServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void openConnection(IPlayer player, VoiceChannel channel) {
    if (lavaLink != null) {
        lavaLink.getLink(channel.getGuild()).connect(channel);
    } else {
        AudioManager audioManager = channel.getGuild().getAudioManager();
        if (audioManager.getConnectedChannel() == null) {
            audioManager.setSendingHandler(new GuildAudioSendHandler(player));
        }
        channel.getGuild().getAudioManager().openAudioConnection(channel);
    }
}
 
Example #5
Source File: WebSocketSendingThread.java    From JDA with Apache License 2.0 5 votes vote down vote up
protected DataObject newVoiceOpen(AudioManager manager, long channel, long guild)
{
    return DataObject.empty()
        .put("op", WebSocketCode.VOICE_STATE)
        .put("d", DataObject.empty()
            .put("guild_id", guild)
            .put("channel_id", channel)
            .put("self_mute", manager.isSelfMuted())
            .put("self_deaf", manager.isSelfDeafened()));
}
 
Example #6
Source File: WebSocketSendingThread.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void handleAudioRequest(ConnectionRequest audioRequest)
{
    long channelId = audioRequest.getChannelId();
    long guildId = audioRequest.getGuildIdLong();
    Guild guild = api.getGuildById(guildId);
    if (guild == null)
    {
        LOG.debug("Discarding voice request due to null guild {}", guildId);
        // race condition on guild delete, avoid NPE on DISCONNECT requests
        queuedAudioConnections.remove(guildId);
        return;
    }
    ConnectionStage stage = audioRequest.getStage();
    AudioManager audioManager = guild.getAudioManager();
    DataObject packet;
    switch (stage)
    {
        case RECONNECT:
        case DISCONNECT:
            packet = newVoiceClose(guildId);
            break;
        default:
        case CONNECT:
            packet = newVoiceOpen(audioManager, channelId, guild.getIdLong());
    }
    LOG.debug("Sending voice request {}", packet);
    if (send(packet.toString()))
    {
        //If we didn't get RateLimited, Next request attempt will be 2 seconds from now
        // we remove it in VoiceStateUpdateHandler once we hear that it has updated our status
        // in 2 seconds we will attempt again in case we did not receive an update
        audioRequest.setNextAttemptEpoch(System.currentTimeMillis() + 2000);
        //If we are already in the correct state according to voice state
        // we will not receive a VOICE_STATE_UPDATE that would remove it
        // thus we update it here
        final GuildVoiceState voiceState = guild.getSelfMember().getVoiceState();
        client.updateAudioConnection0(guild.getIdLong(), voiceState.getChannel());
    }
}
 
Example #7
Source File: JDAImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void closeAudioConnections()
{
    List<AudioManagerImpl> managers;
    AbstractCacheView<AudioManager> view = getAudioManagersView();
    try (UnlockHook hook = view.writeLock())
    {
        managers = view.stream()
           .map(AudioManagerImpl.class::cast)
           .collect(Collectors.toList());
        view.clear();
    }

    managers.forEach(m -> m.closeAudioConnection(ConnectionStatus.SHUTTING_DOWN));
}
 
Example #8
Source File: SoundPlayerImpl.java    From DiscordSoundboard with Apache License 2.0 5 votes vote down vote up
/**
 * Play the provided File object
 *
 * @param audioFile    - The File object to play.
 * @param guild        - The guild (discord server) the playback is going to happen in.
 * @param repeatNumber - The number of times to repeat the audio file.
 */
private void playFile(File audioFile, Guild guild, int repeatNumber) {
    if (guild == null) {
        LOG.fatal("Guild is null or you're not in a voice channel the bot has permission to access. Have you added your bot to a guild? https://discordapp.com/developers/docs/topics/oauth2");
    } else {
        AudioManager audioManager = guild.getAudioManager();
        AudioSendHandler audioSendHandler = new MyAudioSendHandler(musicPlayer);
        audioManager.setSendingHandler(audioSendHandler);

        playFileString(audioFile.getAbsolutePath());
    }
}
 
Example #9
Source File: SoundPlayerImpl.java    From DiscordSoundboard with Apache License 2.0 5 votes vote down vote up
/**
     * Moves to the specified voice channel.
     *
     * @param channel - The channel specified.
     */
    private void moveToChannel(VoiceChannel channel, Guild guild) {
//        boolean hasPermissionToSpeak = PermissionUtil.checkPermission(bot.getSelfUser(), Permission.VOICE_SPEAK);
//        if (hasPermissionToSpeak) {
        AudioManager audioManager = guild.getAudioManager();
        if (audioManager.isConnected()) {
            if (audioManager.isAttemptingToConnect()) {
                audioManager.closeAudioConnection();
            }
            audioManager.openAudioConnection(channel);
        } else {
            audioManager.openAudioConnection(channel);
        }

        int i = 0;
        int waitTime = 100;
        int maxIterations = 40;
        //Wait for the audio connection to be ready before proceeding.
        synchronized (this) {
            while (!audioManager.isConnected()) {
                try {
                    wait(waitTime);
                    i++;
                    if (i >= maxIterations) {
                        break; //break out if after 1 second it doesn't get a connection;
                    }
                } catch (InterruptedException e) {
                    LOG.warn("Waiting for audio connection was interrupted.");
                }
            }
        }
//        } else {
//            throw new SoundPlaybackException("The bot does not have permission to speak in the requested channel: " + channel.getName() + ".");
//        }
    }
 
Example #10
Source File: Main.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private static void connectToFirstVoiceChannel(AudioManager audioManager) {
  if (!audioManager.isConnected() && !audioManager.isAttemptingToConnect()) {
    for (VoiceChannel voiceChannel : audioManager.getGuild().getVoiceChannels()) {
      audioManager.openAudioConnection(voiceChannel);
      break;
    }
  }
}
 
Example #11
Source File: DefaultAudioServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isConnected(Guild guild) {
    if (lavaLink != null) {
        Link link = lavaLink.getLink(guild);
        return link.getState() == Link.State.CONNECTED || link.getState() == Link.State.CONNECTING;
    } else {
        AudioManager audioManager = guild.getAudioManager();
        return audioManager != null && (audioManager.isConnected() || audioManager.isAttemptingToConnect());
    }
}
 
Example #12
Source File: LavalinkManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public void openConnection(VoiceChannel channel) {
    final AudioManager audioManager = channel.getGuild().getAudioManager();

    // Turn on the deafen icon for the bot
    audioManager.setSelfDeafened(true);

    if (isEnabled()) {
        lavalink.getLink(channel.getGuild()).connect(channel);
    } else {
        audioManager.openAudioConnection(channel);
    }
}
 
Example #13
Source File: JDA.java    From JDA with Apache License 2.0 4 votes vote down vote up
/**
 * Immutable list of all created {@link net.dv8tion.jda.api.managers.AudioManager AudioManagers} for this JDA instance!
 *
 * @return Immutable list of all created AudioManager instances
 */
@Nonnull
default List<AudioManager> getAudioManagers()
{
    return getAudioManagerCache().asList();
}
 
Example #14
Source File: GuildSetupNode.java    From JDA with Apache License 2.0 4 votes vote down vote up
private void updateAudioManagerReference(GuildImpl guild)
{
    JDAImpl api = getController().getJDA();
    AbstractCacheView<AudioManager> managerView = api.getAudioManagersView();
    try (UnlockHook hook = managerView.writeLock())
    {
        TLongObjectMap<AudioManager> audioManagerMap = managerView.getMap();
        AudioManagerImpl mng = (AudioManagerImpl) audioManagerMap.get(id);
        if (mng == null)
            return;
        ConnectionListener listener = mng.getConnectionListener();
        final AudioManagerImpl newMng = new AudioManagerImpl(guild);
        newMng.setSelfMuted(mng.isSelfMuted());
        newMng.setSelfDeafened(mng.isSelfDeafened());
        newMng.setQueueTimeout(mng.getConnectTimeout());
        newMng.setSendingHandler(mng.getSendingHandler());
        newMng.setReceivingHandler(mng.getReceivingHandler());
        newMng.setConnectionListener(listener);
        newMng.setAutoReconnect(mng.isAutoReconnect());

        if (mng.isConnected())
        {
            final long channelId = mng.getConnectedChannel().getIdLong();

            final VoiceChannel channel = api.getVoiceChannelById(channelId);
            if (channel != null)
            {
                if (mng.isConnected())
                    mng.closeAudioConnection(ConnectionStatus.ERROR_CANNOT_RESUME);
            }
            else
            {
                //The voice channel is not cached. It was probably deleted.
                api.getClient().removeAudioConnection(id);
                if (listener != null)
                    listener.onStatusChange(ConnectionStatus.DISCONNECTED_CHANNEL_DELETED);
            }
        }
        audioManagerMap.put(id, newMng);
    }
}
 
Example #15
Source File: JDAImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public CacheView<AudioManager> getAudioManagerCache()
{
    return audioManagers;
}
 
Example #16
Source File: JDAImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
public AbstractCacheView<AudioManager> getAudioManagersView()
{
    return audioManagers;
}
 
Example #17
Source File: JDA.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * {@link net.dv8tion.jda.api.utils.cache.CacheView CacheView} of
 * all cached {@link net.dv8tion.jda.api.managers.AudioManager AudioManagers} created for this JDA instance.
 * <br>AudioManagers are created when first retrieved via {@link net.dv8tion.jda.api.entities.Guild#getAudioManager() Guild.getAudioManager()}.
 * <u>Using this will perform better than calling {@code Guild.getAudioManager()} iteratively as that would cause many useless audio managers to be created!</u>
 *
 * <p>AudioManagers are cross-session persistent!
 *
 * @return {@link net.dv8tion.jda.api.utils.cache.CacheView CacheView}
 */
@Nonnull
CacheView<AudioManager> getAudioManagerCache();