com.sedmelluq.discord.lavaplayer.player.AudioPlayer Java Examples

The following examples show how to use com.sedmelluq.discord.lavaplayer.player.AudioPlayer. 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: TrackScheduler.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void onTrackStart(AudioPlayer player, AudioTrack track) {
    final TrackUserData data = track.getUserData(TrackUserData.class);

    // If the track was a skipped track or we announce tracks
    if (data.getWasFromSkip() || this.guildMusicManager.isAnnounceTracks()) {
        // Reset the was from skip status
        data.setWasFromSkip(false);

        final EmbedBuilder message = AudioTrackKt.toEmbed(
            track,
            this.guildMusicManager,
            getInstance().getShardManager(),
            false
        );

        sendEmbed(this.guildMusicManager.getLatestChannel(), message);
    }
}
 
Example #2
Source File: MusicManager.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets the {@link GuildMusic} corresponding to the provided {@code guildId}. If there is none,
 * a new one is created and a request to join the {@link VoiceChannel} corresponding to the provided
 * {@code voiceChannelId} is sent.
 */
public Mono<GuildMusic> getOrCreate(GatewayDiscordClient gateway, Snowflake guildId, Snowflake voiceChannelId) {
    return Mono.justOrEmpty(this.getGuildMusic(guildId))
            .switchIfEmpty(Mono.defer(() -> {
                final AudioPlayer audioPlayer = this.audioPlayerManager.createPlayer();
                audioPlayer.addListener(new TrackEventListener(guildId));
                final LavaplayerAudioProvider audioProvider = new LavaplayerAudioProvider(audioPlayer);

                return this.joinVoiceChannel(gateway, guildId, voiceChannelId, audioProvider)
                        .flatMap(ignored -> DatabaseManager.getGuilds().getDBGuild(guildId))
                        .map(DBGuild::getSettings)
                        .map(Settings::getDefaultVol)
                        .map(volume -> new TrackScheduler(audioPlayer, volume))
                        .map(trackScheduler -> new GuildMusic(gateway, guildId, trackScheduler))
                        .doOnNext(guildMusic -> {
                            this.guildMusics.put(guildId, guildMusic);
                            LOGGER.debug("{Guild ID: {}} Guild music created", guildId.asLong());
                        });
            }));
}
 
Example #3
Source File: PlayerManagerTestTools.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
public static long consumeTrack(AudioPlayer player) throws Exception {
  ByteBuffer buffer = ByteBuffer.allocate(960 * 2 * 2);

  MutableAudioFrame frame = new MutableAudioFrame();
  frame.setBuffer(buffer);

  CRC32 crc = new CRC32();
  int count = 0;

  while (player.getPlayingTrack() != null && player.provide(frame, 10, TimeUnit.SECONDS)) {
    buffer.flip();
    crc.update(buffer.array(), buffer.position(), buffer.remaining());
    count++;
  }

  System.out.println("Consumed " + count + " samples");

  return crc.getValue();
}
 
Example #4
Source File: TrackManager.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
    try {
        Guild g = queue.poll().getAuthor().getGuild();
        if (queue.isEmpty()) {
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    g.getAudioManager().closeAudioConnection();
                }
            }, 500);
        } else {
            player.playTrack(queue.element().getTrack());
        }
    } catch (Exception e) {}
}
 
Example #5
Source File: EventEmitter.java    From Lavalink with MIT License 6 votes vote down vote up
@Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
    JSONObject out = new JSONObject();
    out.put("op", "event");
    out.put("type", "TrackExceptionEvent");
    out.put("guildId", linkPlayer.getGuildId());
    try {
        out.put("track", Util.toMessage(audioPlayerManager, track));
    } catch (IOException e) {
        out.put("track", JSONObject.NULL);
    }

    out.put("error", exception.getMessage());

    linkPlayer.getSocket().send(out);
}
 
Example #6
Source File: Music.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {

    if (getTrackManager(guild).getQueuedTracks().size() < 2 && endlessMode) {
        endlessList.forEach(t -> getTrackManager(guild).queue(t, endlessAuthor));
        if (guild.getTextChannelsByName(SSSS.getMUSICCHANNEL(guild), true).size() > 0)
            guild.getTextChannelsByName(SSSS.getMUSICCHANNEL(guild), true).get(0).sendMessage(MSGS.success().setDescription("Repeated queue. *(endless mode)*").build()).queue();
    }

    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            if (player.getPlayingTrack() == null) {
                if (guild.getTextChannelsByName(SSSS.getMUSICCHANNEL(guild), true).size() > 0) {
                    guild.getTextChannelsByName(SSSS.getMUSICCHANNEL(guild), true).get(0).getManager().setTopic(
                            "-music help"
                    ).queue();
                }
            }
        }
    }, 500);

}
 
Example #7
Source File: LocalPlayerDemo.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws LineUnavailableException, IOException {
  AudioPlayerManager manager = new DefaultAudioPlayerManager();
  AudioSourceManagers.registerRemoteSources(manager);
  manager.getConfiguration().setOutputFormat(COMMON_PCM_S16_BE);

  AudioPlayer player = manager.createPlayer();

  manager.loadItem("ytsearch: epic soundtracks", new FunctionalResultHandler(null, playlist -> {
    player.playTrack(playlist.getTracks().get(0));
  }, null, null));

  AudioDataFormat format = manager.getConfiguration().getOutputFormat();
  AudioInputStream stream = AudioPlayerInputStream.createStream(player, format, 10000L, false);
  SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class, stream.getFormat());
  SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);

  line.open(stream.getFormat());
  line.start();

  byte[] buffer = new byte[COMMON_PCM_S16_BE.maximumChunkSize()];
  int chunkSize;

  while ((chunkSize = stream.read(buffer)) >= 0) {
    line.write(buffer, 0, chunkSize);
  }
}
 
Example #8
Source File: TrackMixer.java    From andesite-node with MIT License 5 votes vote down vote up
Player(AudioPlayer player, AndesitePlayer parent, String key) {
    this.player = player;
    this.parent = parent;
    this.key = key;
    frame.setBuffer(buffer);
    buffer.limit(frame.getDataLength());
    this.player.addListener(frameLossTracker);
}
 
Example #9
Source File: PlayerListener.java    From FlareBot with MIT License 5 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer aplayer, AudioTrack atrack, AudioTrackEndReason reason) {
    GuildWrapper wrapper = FlareBotManager.instance().getGuild(player.getGuildId());

    if (wrapper == null) return;

    // No song on next
    if (player.getPlaylist().isEmpty()) {
        FlareBotManager.instance().getLastActive().put(Long.parseLong(player.getGuildId()), System.currentTimeMillis());
    }

    VoteUtil.remove(SkipCommand.getSkipUUID(), wrapper.getGuild());

    if (wrapper.isSongnickEnabled()) {
        if (GuildUtils.canChangeNick(player.getGuildId())) {
            Guild c = wrapper.getGuild();
            if (c == null) {
                wrapper.setSongnick(false);
            } else {
                if (player.getPlaylist().isEmpty())
                    c.getController().setNickname(c.getSelfMember(), null).queue();
            }
        } else {
            if (!GuildUtils.canChangeNick(player.getGuildId())) {
                MessageUtils.sendPM(Getters.getGuildById(player.getGuildId()).getOwner().getUser(),
                        "FlareBot can't change it's nickname so SongNick has been disabled!");
            }
        }
    }
}
 
Example #10
Source File: Music.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
private AudioPlayer createPlayer(Guild guild) {
    AudioPlayer nPlayer = myManager.createPlayer();
    TrackManager manager = new TrackManager(nPlayer);
    nPlayer.addListener(manager);
    guild.getAudioManager().setSendingHandler(new AudioPlayerSendHandler(nPlayer));
    players.put(guild.getId(), new AbstractMap.SimpleEntry<>(nPlayer, manager));
    return nPlayer;
}
 
Example #11
Source File: TrackStuckEvent.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * @param player Audio player
 * @param track Audio track where the exception occurred
 * @param thresholdMs The wait threshold that was exceeded for this event to trigger
 */
public TrackStuckEvent(AudioPlayer player, AudioTrack track, long thresholdMs, StackTraceElement[] stackTrace) {
  super(player);
  this.track = track;
  this.thresholdMs = thresholdMs;
  this.stackTrace = stackTrace;
}
 
Example #12
Source File: TrackScheduler.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
    final Throwable rootCause = ExceptionUtils.getRootCause(exception);
    final Throwable finalCause = rootCause == null ? exception : rootCause;

    if (finalCause == null || finalCause.getMessage() == null) {
        this.messageDebouncer.accept("Something went terribly wrong when playing track with identifier `" + track.getIdentifier() +
            "`\nPlease contact the developers asap with the identifier in the message above");
        return;
    }

    if (finalCause.getMessage().contains("Something went wrong when decoding the track.")) {
        return;
    }

    this.messageDebouncer.accept("Something went wrong while playing the track, please contact the devs if this happens a lot.\n" +
        "Details: " + finalCause);

    // old shit
    /*if (exception.severity != FriendlyException.Severity.COMMON) {
        final TextChannel tc = guildMusicManager.getLatestChannel();
        final Guild g = tc == null ? null : tc.getGuild();

        if (g != null) {
            final AudioTrackInfo info = track.getInfo();
            final String error = String.format(
                "Guild %s (%s) had an FriendlyException on track \"%s\" by \"%s\" (source %s) (%s)",
                g.getName(),
                g.getId(),
                info.title,
                info.author,
                track.getSourceManager().getSourceName(),
                info.identifier
            );

            logger.error(TextColor.RED + error + TextColor.RESET, exception);
        }

    }*/
}
 
Example #13
Source File: TrackScheduler.java    From Yui with Apache License 2.0 5 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason)
{
    this.lastTrack = track;
    // Only start the next track if the end reason is suitable for it (FINISHED or LOAD_FAILED)
    if (endReason.mayStartNext)
    {
        if (repeating)
            player.startTrack(lastTrack.makeClone(), false);
        else
            nextTrack();
    }

}
 
Example #14
Source File: EventEmitter.java    From andesite-node with MIT License 5 votes vote down vote up
@Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
    sendEvent.accept(event("TrackExceptionEvent", track)
            .put("error", exception.getMessage())
            .put("exception", RequestUtils.encodeThrowableShort(exception)));
    sendPlayerUpdate();
}
 
Example #15
Source File: EventEmitter.java    From andesite-node with MIT License 5 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
    sendEvent.accept(event("TrackEndEvent", track)
            .put("reason", endReason.toString())
            .put("mayStartNext", endReason.mayStartNext));
    sendPlayerUpdate();
}
 
Example #16
Source File: Music.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
private AudioPlayer getPlayer(Guild guild) {
    AudioPlayer p;
    if (hasPlayer(guild)) {
        p = players.get(guild.getId()).getKey();
    } else {
        p = createPlayer(guild);
    }
    return p;
}
 
Example #17
Source File: AudioPlayerSendHandler.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
    this.audioPlayer = audioPlayer;
    if (ExtraRuntimeOptions.DISABLE_NON_ALLOCATING_BUFFER) {
        this.frame = null;
    } else {
        this.frame = new MutableAudioFrame();
        frame.setFormat(StandardAudioDataFormats.DISCORD_OPUS);
        frame.setBuffer(ByteBuffer.allocate(StandardAudioDataFormats.DISCORD_OPUS.maximumChunkSize()));
    }
}
 
Example #18
Source File: RemoteNodeManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
  AudioTrackExecutor executor = ((InternalAudioTrack) track).getActiveExecutor();

  if (endReason != AudioTrackEndReason.FINISHED && executor instanceof RemoteAudioTrackExecutor) {
    for (RemoteNodeProcessor processor : activeProcessors) {
      processor.trackEnded((RemoteAudioTrackExecutor) executor, true);
    }
  }
}
 
Example #19
Source File: TrackEventListener.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onTrackStart(AudioPlayer player, AudioTrack track) {
    Mono.justOrEmpty(MusicManager.getInstance().getGuildMusic(this.guildId))
            .flatMap(guildMusic -> {
                final String message = String.format(Emoji.MUSICAL_NOTE + " Currently playing: **%s**",
                        FormatUtils.trackName(track.getInfo()));
                return guildMusic.getMessageChannel()
                        .flatMap(channel -> DiscordUtils.sendMessage(message, channel));
            })
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe(null, ExceptionHandler::handleUnknownError);
}
 
Example #20
Source File: TrackEventListener.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
    Mono.justOrEmpty(MusicManager.getInstance().getGuildMusic(this.guildId))
            .filter(ignored -> endReason == AudioTrackEndReason.FINISHED)
            // Everything seems fine, reset error counter.
            .doOnNext(ignored -> this.errorCount.set(0))
            .flatMap(ignored -> this.nextOrEnd())
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe(null, ExceptionHandler::handleUnknownError);
}
 
Example #21
Source File: StreamAudioPlayer.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
public StreamAudioPlayer(AudioPlayer fallback, StreamAudioPlayerManager manager) {
  this.fallback = fallback;
  this.manager = manager;
  this.lock = new Object();
  this.listeners = new ArrayList<>();
  this.detachListener = new DetachListener();

  fallback.addListener(new StreamEventListener());
}
 
Example #22
Source File: TrackEventListener.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onTrackStuck(AudioPlayer player, AudioTrack track, long thresholdMs) {
    LOGGER.info("{Guild ID: {}} Music stuck, skipping it", this.guildId.asLong());
    Mono.justOrEmpty(MusicManager.getInstance().getGuildMusic(this.guildId))
            .flatMap(GuildMusic::getMessageChannel)
            .flatMap(channel -> DiscordUtils.sendMessage(Emoji.RED_EXCLAMATION + " Music seems stuck, I'll "
                    + "try to play the next available song.", channel))
            .then(this.nextOrEnd())
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe(null, ExceptionHandler::handleUnknownError);
}
 
Example #23
Source File: TrackScheduler.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
  // Only start the next track if the end reason is suitable for it (FINISHED or LOAD_FAILED)
  if (endReason.mayStartNext) {
    nextTrack();
  }
}
 
Example #24
Source File: AudioPlayerSendHandler.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * @param audioPlayer Audio player to wrap.
 */
public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
  this.audioPlayer = audioPlayer;
  this.buffer = ByteBuffer.allocate(1024);
  this.frame = new MutableAudioFrame();
  this.frame.setBuffer(buffer);
}
 
Example #25
Source File: MusicScheduler.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
public MusicScheduler(AudioPlayer player, MessageDispatcher messageDispatcher, ScheduledExecutorService executorService) {
  this.player = player;
  this.messageDispatcher = messageDispatcher;
  this.executorService = executorService;
  this.queue = new LinkedBlockingDeque<>();
  this.boxMessage = new AtomicReference<>();
  this.creatingBoxMessage = new AtomicBoolean();

  executorService.scheduleAtFixedRate(this, 3000L, 15000L, TimeUnit.MILLISECONDS);
}
 
Example #26
Source File: StreamInstance.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
public StreamInstance(AudioTrack track, AudioPlayer trackPlayer, int maximumFrameCount) {
  this.track = track;
  this.trackPlayer = trackPlayer;
  this.maximumFrameCount = maximumFrameCount;
  this.ringBuffer = new AudioFrame[maximumFrameCount];
  this.cursors = new HashSet<>();
}
 
Example #27
Source File: Player.java    From Lavalink with MIT License 5 votes vote down vote up
@Override
public void onTrackStart(AudioPlayer player, AudioTrack track) {
    if (myFuture == null || myFuture.isCancelled()) {
        myFuture = socketContext.getPlayerUpdateService().scheduleAtFixedRate(() -> {
            if (socketContext.getSessionPaused()) return;

            SocketServer.Companion.sendPlayerUpdate(socketContext, this);
        }, 0, 5, TimeUnit.SECONDS);
    }
}
 
Example #28
Source File: AudioLossCounter.java    From Lavalink with MIT License 5 votes vote down vote up
@Override
public void onTrackStart(AudioPlayer __, AudioTrack ___) {
    lastTrackStarted = System.currentTimeMillis();

    if (lastTrackStarted - lastTrackEnded > ACCEPTABLE_TRACK_SWITCH_TIME
            || playingSince == Long.MAX_VALUE) {
        playingSince = System.currentTimeMillis();
        lastTrackEnded = Long.MAX_VALUE;
    }
}
 
Example #29
Source File: MusicScheduler.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
  if (endReason.mayStartNext) {
    startNextTrack(true);
    messageDispatcher.sendMessage(String.format("Track %s finished.", track.getInfo().title));
  }
}
 
Example #30
Source File: AudioListener.java    From DiscordBot with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrackStuck(AudioPlayer audioPlayer, AudioTrack audioTrack, long time) {
	LogHelper.debug("Track stuck.");
}