com.sedmelluq.discord.lavaplayer.track.AudioTrack Java Examples

The following examples show how to use com.sedmelluq.discord.lavaplayer.track.AudioTrack. 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: NicoAudioSourceManager.java    From kyoko with MIT License 6 votes vote down vote up
private AudioTrack loadTrack(String videoId) {
    checkLoggedIn();

    try (HttpInterface httpInterface = getHttpInterface()) {
        try (CloseableHttpResponse response = httpInterface.execute(new HttpGet("https://www.nicovideo.jp/watch/" + videoId))) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new IOException("Unexpected response code from video info: " + statusCode);
            }

            Document document = Jsoup.parse(response.getEntity().getContent(), StandardCharsets.UTF_8.name(), "", Parser.htmlParser());
            return extractTrackFromHtml(videoId, document);
        }
    } catch (IOException e) {
        throw new FriendlyException("Error occurred when extracting video info.", SUSPICIOUS, e);
    }
}
 
Example #2
Source File: YoutubeSearchProvider.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private void extractTrackFromResultEntry(List<AudioTrack> tracks, Element element,
                                         Function<AudioTrackInfo, AudioTrack> trackFactory) {

  Element durationElement = element.select("[class^=video-time]").first();
  Element contentElement = element.select(".yt-lockup-content").first();
  String videoId = element.attr("data-context-item-id");

  if (durationElement == null || contentElement == null || videoId.isEmpty()) {
    return;
  }

  long duration = DataFormatTools.durationTextToMillis(durationElement.text());

  String title = contentElement.select(".yt-lockup-title > a").text();
  String author = contentElement.select(".yt-lockup-byline > a").text();

  AudioTrackInfo info = new AudioTrackInfo(title, author, duration, videoId, false,
      WATCH_URL_PREFIX + videoId);

  tracks.add(trackFactory.apply(info));
}
 
Example #3
Source File: AudioListener.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
@Override
public void onTrackEnd(AudioPlayer audioPlayer, AudioTrack audioTrack, AudioTrackEndReason audioTrackEndReason) {
	if (audioTrackEndReason.equals(AudioTrackEndReason.FINISHED) && audioTrackEndReason.mayStartNext) {
		LogHelper.debug("Track Finished, Playing next.");
		DiscordBot.getInstance().getDiscord().getAudioQueue().playNext();
		return;
	}
	
	if (audioTrackEndReason.equals(AudioTrackEndReason.STOPPED)) {
		LogHelper.debug("Track stopped.");
		return;
	}
	
	if (audioTrackEndReason.equals(AudioTrackEndReason.REPLACED)) {
		LogHelper.debug("Track replaced.");
	}
}
 
Example #4
Source File: GetyarnAudioSourceManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private AudioTrack extractVideoUrlFromPage(AudioReference reference) {
  try (final CloseableHttpResponse response = getHttpInterface().execute(new HttpGet(reference.identifier))) {
    final String html = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
    final Document document = Jsoup.parse(html);

    final AudioTrackInfo trackInfo = AudioTrackInfoBuilder.empty()
        .setUri(reference.identifier)
        .setAuthor("Unknown")
        .setIsStream(false)
        .setIdentifier(document.selectFirst("meta[property=og:video:secure_url]").attr("content"))
        .setTitle(document.selectFirst("meta[property=og:title]").attr("content"))
        .build();

    return createTrack(trackInfo);
  } catch (IOException e) {
    throw new FriendlyException("Failed to load info for yarn clip", SUSPICIOUS, null);
  }
}
 
Example #5
Source File: StreamAudioPlayerManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private boolean loadFromStream(String identifier, AudioLoadResultHandler resultHandler) {
  try {
    StreamInstance stream;

    synchronized (streams) {
      String finalIdentifier = defaultOnNull(resolutionCache.get(identifier), identifier);
      stream = streams.get(finalIdentifier);
    }

    if (stream != null) {
      AudioTrack track = stream.getTrack().makeClone();
      log.debug("Track {} (originally {}) loaded using existing stream.", track.getIdentifier(), identifier);

      resultHandler.trackLoaded(track);
      return true;
    }
  } catch (Exception e) {
    log.error("Error when checking streams for identifier {}.", identifier);
  }

  return false;
}
 
Example #6
Source File: SoundCloudAudioSourceManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioTrack processAsSingleTrack(AudioReference reference) {
  String url = SoundCloudHelper.nonMobileUrl(reference.identifier);

  Matcher trackUrlMatcher = trackUrlPattern.matcher(url);
  if (trackUrlMatcher.matches() && !"likes".equals(trackUrlMatcher.group(2))) {
    return loadFromTrackPage(url);
  }

  Matcher unlistedUrlMatcher = unlistedUrlPattern.matcher(url);
  if (unlistedUrlMatcher.matches()) {
    return loadFromTrackPage(url);
  }

  return null;
}
 
Example #7
Source File: TrackScheduler.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This is a special case for the skip command where it has to announce the next track
 * due to it being a user interaction
 */
public void specialSkipCase() {
    // Get the currently playing track
    final AudioTrack playingTrack = this.player.getPlayingTrack();
    // Set in the data that it was from a skip
    playingTrack.getUserData(TrackUserData.class).setWasFromSkip(true);

    // Seek to the end to start the next track
    // We seek to use the normal flow that allows for repeating as well
    this.player.seekTo(playingTrack.getDuration());
}
 
Example #8
Source File: Main.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private void loadAndPlay(TextChannel channel, final String trackUrl) {
  GuildMusicManager musicManager = getGuildAudioPlayer(channel.getGuild().block());

  playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() {
    @Override
    public void trackLoaded(AudioTrack track) {
      sendMessageToChannel(channel, "Adding to queue " + track.getInfo().title);

      play(channel.getGuild().block(), musicManager, track);
    }

    @Override
    public void playlistLoaded(AudioPlaylist playlist) {
      AudioTrack firstTrack = playlist.getSelectedTrack();

      if (firstTrack == null) {
        firstTrack = playlist.getTracks().get(0);
      }

      sendMessageToChannel(channel, "Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")");

      play(channel.getGuild().block(), musicManager, firstTrack);
    }

    @Override
    public void noMatches() {
      sendMessageToChannel(channel, "Nothing found by " + trackUrl);
    }

    @Override
    public void loadFailed(FriendlyException exception) {
      sendMessageToChannel(channel, "Could not play: " + exception.getMessage());
    }
  });
}
 
Example #9
Source File: RemoteNodeProcessor.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * Start playing a track through this remote node.
 * @param executor The executor of the track
 */
public void startPlaying(RemoteAudioTrackExecutor executor) {
  AudioTrack track = executor.getTrack();

  if (playingTracks.putIfAbsent(executor.getExecutorId(), executor) == null) {
    long position = executor.getNextInputTimecode();
    log.info("Sending request to play {} {} from position {}", track.getIdentifier(), executor.getExecutorId(), position);

    queuedMessages.add(new TrackStartRequestMessage(executor.getExecutorId(), track.getInfo(), playerManager.encodeTrackDetails(track),
        executor.getVolume(), executor.getConfiguration(), position));
  }
}
 
Example #10
Source File: YoutubeSearchProvider.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioItem extractSearchResults(Document document, String query,
                                       Function<AudioTrackInfo, AudioTrack> trackFactory) {

  List<AudioTrack> tracks = new ArrayList<>();
  Elements resultsSelection = document.select("#page > #content #results");
  if (!resultsSelection.isEmpty()) {
    for (Element results : resultsSelection) {
      for (Element result : results.select(".yt-lockup-video")) {
        if (!result.hasAttr("data-ad-impressions") && result.select(".standalone-ypc-badge-renderer-label").isEmpty()) {
          extractTrackFromResultEntry(tracks, result, trackFactory);
        }
      }
    }
  } else {
    log.debug("Attempting to parse results page as polymer");
    try {
      tracks = polymerExtractTracks(document, trackFactory);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  if (tracks.isEmpty()) {
    return AudioReference.NO_TRACK;
  } else {
    return new BasicAudioPlaylist("Search results for: " + query, tracks, null, true);
  }
}
 
Example #11
Source File: MusicScheduler.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
public void playNow(AudioTrack audioTrack, boolean clearQueue) {
  if (clearQueue) {
    queue.clear();
  }

  queue.addFirst(audioTrack);
  startNextTrack(false);
}
 
Example #12
Source File: TrackBoxBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private static String buildFirstLine(int width, AudioTrack track) {
  StringBuilder builder = new StringBuilder();
  String title = track.getInfo().title;
  int titleWidth = width - 7;

  if (title.length() > titleWidth) {
    builder.append(title.substring(0, titleWidth - 3));
    builder.append("...");
  } else {
    builder.append(title);
  }

  return builder.toString();
}
 
Example #13
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 #14
Source File: LavalinkPlayer.java    From Lavalink-Client with MIT License 5 votes vote down vote up
/**
 * Invoked by {@link Link} to make sure we keep playing music on the new node
 * <p>
 * Used when we are moved to a new socket
 */
public void onNodeChange() {
    AudioTrack track = getPlayingTrack();
    if (track != null) {
        track.setPosition(getTrackPosition());
        playTrack(track);
    }

}
 
Example #15
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 #16
Source File: YoutubeMixProvider.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private AudioTrack findSelectedTrack(List<AudioTrack> tracks, String selectedVideoId) {
  if (selectedVideoId != null) {
    for (AudioTrack track : tracks) {
      if (selectedVideoId.equals(track.getIdentifier())) {
        return track;
      }
    }
  }

  return null;
}
 
Example #17
Source File: RemoteAudioTrackExecutor.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * @param track Audio track to play
 * @param configuration Configuration for audio processing
 * @param remoteNodeManager Manager of remote nodes
 * @param volumeLevel Mutable volume level
 */
public RemoteAudioTrackExecutor(AudioTrack track, AudioConfiguration configuration,
                                RemoteNodeManager remoteNodeManager, AtomicInteger volumeLevel) {

  this.track = track;
  this.configuration = configuration.copy();
  this.remoteNodeManager = remoteNodeManager;
  this.volumeLevel = volumeLevel;
  this.executorId = System.nanoTime();
  this.frameBuffer = configuration.getFrameBufferFactory().create(BUFFER_DURATION_MS, configuration.getOutputFormat(), null);
}
 
Example #18
Source File: TrackData.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public static String getArtwork(AudioTrack track) {
    AudioTrackInfo info = track.getInfo();
    if (StringUtils.isNotBlank(info.getArtworkUrl())) {
        return info.getArtworkUrl();
    }
    TrackData trackData = get(track);
    if (trackData.getPlaylistItem() != null && StringUtils.isNotBlank(trackData.getPlaylistItem().getArtworkUri())) {
        return trackData.getPlaylistItem().getArtworkUri();
    }
    return null;
}
 
Example #19
Source File: RemoteNodeProcessor.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isPlayingTrack(AudioTrack track) {
  AudioTrackExecutor executor = ((InternalAudioTrack) track).getActiveExecutor();

  if (executor instanceof RemoteAudioTrackExecutor) {
    return playingTracks.containsKey(((RemoteAudioTrackExecutor) executor).getExecutorId());
  }

  return false;
}
 
Example #20
Source File: LavalinkTrackLoader.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
private static AudioTrack decode(AudioPlayerManager manager, String track) {
    try {
        return manager.decodeTrack(new MessageInput(new ByteArrayInputStream(
                Base64.getDecoder().decode(track)
        ))).decodedTrack;
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to decode track", e);
    }
}
 
Example #21
Source File: AudioMessageManager.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private String getTextProgress(PlaybackInstance instance, AudioTrack track, boolean bonusActive) {
    StringBuilder builder = new StringBuilder();

    boolean closeDuration = false;
    if (bonusActive && instance.getPlayer().getPlayingTrack() != null) {
        if (!track.getInfo().isStream) {
            double progress = (double) instance.getPosition() / (double) track.getDuration();
            builder.append(AudioUtils.getProgressString((int) (progress * 100))).append(" ");
        }
        builder.append("`").append(CommonUtils.formatDuration(instance.getPosition()));
        closeDuration = true;
    }
    if (!track.getInfo().isStream) {
        if (track.getDuration() >= 0) {
            if (bonusActive && builder.length() > 0) {
                builder.append(" / ");
            }
            builder.append(CommonUtils.formatDuration(track.getDuration()));
        }
    }
    if (closeDuration) {
        builder.append("`");
    }
    if (track.getInfo().isStream) {
        builder.append(String.format(bonusActive ? " (%s)" : "%s",
                messageService.getMessage("discord.command.audio.panel.stream")));
    }
    return builder.toString();
}
 
Example #22
Source File: DefaultAudioPlayerManager.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes an audio track from a byte array.
 * @param trackInfo Track info for the track to decode
 * @param buffer Byte array containing the encoded track
 * @return Decoded audio track
 */
public AudioTrack decodeTrackDetails(AudioTrackInfo trackInfo, byte[] buffer) {
  try {
    DataInput input = new DataInputStream(new ByteArrayInputStream(buffer));
    return decodeTrackDetails(trackInfo, input);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #23
Source File: Music.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
private void loadTrack(String identifier, Member author, Message msg) {


        Guild guild = author.getGuild();
        getPlayer(guild);

        msg.getTextChannel().sendTyping().queue();
        myManager.setFrameBufferDuration(5000);
        myManager.loadItemOrdered(guild, identifier, new AudioLoadResultHandler() {

            @Override
            public void trackLoaded(AudioTrack track) {

                getTrackManager(guild).queue(track, author);
            }

            @Override
            public void playlistLoaded(AudioPlaylist playlist) {
                if (playlist.getSelectedTrack() != null) {
                    trackLoaded(playlist.getSelectedTrack());
                } else if (playlist.isSearchResult()) {
                    trackLoaded(playlist.getTracks().get(0));
                } else {

                    for (int i = 0; i < Math.min(playlist.getTracks().size(), PLAYLIST_LIMIT); i++) {
                        getTrackManager(guild).queue(playlist.getTracks().get(i), author);
                    }
                }
            }

            @Override
            public void noMatches() {
            }

            @Override
            public void loadFailed(FriendlyException exception) {
            }
        });
    }
 
Example #24
Source File: TrackManager.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
public void queue(AudioTrack track, Member author) {
    AudioInfo info = new AudioInfo(track, author);
    queue.add(info);

    if (player.getPlayingTrack() == null) {
        player.playTrack(track);
    }
}
 
Example #25
Source File: AudioUtils.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static String getQueueList(ConcurrentLinkedDeque<AudioTrack> queue) {
    StringBuilder sb = new StringBuilder();
    int n = 1;
    for (AudioTrack audioTrack : queue) {
        long aDuration = audioTrack.getDuration();
        String duration = String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes(aDuration),
                TimeUnit.MILLISECONDS.toSeconds(aDuration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(aDuration))
        );

        User dj = audioTrack.getUserData() != null ? MantaroBot.getInstance().getShardManager()
                .getUserById(String.valueOf(audioTrack.getUserData())) : null;

        sb.append("**")
                .append(n)
                .append(". [")
                .append(StringUtils.limit(audioTrack.getInfo().title, 30))
                .append("](")
                .append(audioTrack.getInfo().uri)
                .append(")** (")
                .append(duration)
                .append(")")
                .append(dj != null ? " **[" + dj.getName() + "]**" : "")
                .append("\n");
        n++;
    }
    return sb.toString();
}
 
Example #26
Source File: UserContextAudioPlayerManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private AudioItem checkSourcesForItemOnce(AudioReference reference, AudioLoadResultHandler resultHandler, boolean[] reported, boolean isPatron) {
    for (final AudioSourceManager sourceManager : sourceManagers.get()) {
        if (reference.containerDescriptor != null && !(sourceManager instanceof ProbingAudioSourceManager)) {
            continue;
        }

        final AudioItem item;

        if (sourceManager instanceof SpotifyAudioSourceManager) {
            item = ((SpotifyAudioSourceManager) sourceManager).loadItem(reference, isPatron);
        } else {
            item = sourceManager.loadItem(this, reference);
        }

        if (item != null) {
            if (item instanceof AudioTrack) {
                log.debug("Loaded a track with identifier {} using {}.", reference.identifier, sourceManager.getClass().getSimpleName());
                reported[0] = true;
                resultHandler.trackLoaded((AudioTrack) item);
            } else if (item instanceof AudioPlaylist) {
                log.debug("Loaded a playlist with identifier {} using {}.", reference.identifier, sourceManager.getClass().getSimpleName());
                reported[0] = true;
                resultHandler.playlistLoaded((AudioPlaylist) item);
            }
            return item;
        }
    }

    return null;
}
 
Example #27
Source File: JbAudioPlayerManagerImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AudioTrack decodeTrack(byte[] data) {
    if (ArrayUtils.isEmpty(data)) {
        return null;
    }
    try (ByteArrayInputStream stream = new ByteArrayInputStream(data)) {
        DecodedTrackHolder holder = decodeTrack(new MessageInput(stream));
        return holder != null && holder.decodedTrack != null ? holder.decodedTrack : null;
    } catch (IOException e) {
        log.warn("Could not decode track");
    }
    return null;
}
 
Example #28
Source File: PlayerManagerTestTools.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
public static AudioTrack loadTrack(AudioPlayerManager manager, String identifier) throws Exception {
  CompletableFuture<AudioTrack> result = new CompletableFuture<>();

  manager.loadItem(identifier, new FunctionalResultHandler(
      result::complete,
      (playlist) -> result.completeExceptionally(new IllegalArgumentException()),
      () -> result.completeExceptionally(new NoSuchElementException()),
      result::completeExceptionally
  ));

  return result.get(10, TimeUnit.SECONDS);
}
 
Example #29
Source File: AudioLoadResultListener.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void trackLoaded(AudioTrack audioTrack) {
    LOGGER.debug("{Guild ID: {}} Track loaded: {}", this.guildId.asLong(), audioTrack.hashCode());
    Mono.justOrEmpty(MusicManager.getInstance().getGuildMusic(this.guildId))
            .filter(guildMusic -> !guildMusic.getTrackScheduler().startOrQueue(audioTrack, this.insertFirst))
            .flatMap(GuildMusic::getMessageChannel)
            .flatMap(channel -> DiscordUtils.sendMessage(String.format(
                    Emoji.MUSICAL_NOTE + " **%s** has been added to the playlist.",
                    FormatUtils.trackName(audioTrack.getInfo())), channel))
            .then(this.terminate())
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe(null, ExceptionHandler::handleUnknownError);
}
 
Example #30
Source File: RewindCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected boolean doInternal(GuildMessageReceivedEvent message, TrackRequest request, long millis) {
    PlaybackInstance instance = playerService.get(message.getGuild());
    AudioTrack track = request.getTrack();
    long position = instance.getPosition();
    millis = Math.min(position, millis);
    if (instance.seek(position - millis)) {
        messageManager.onMessage(message.getChannel(), "discord.command.audio.rewind",
                messageManager.getTitle(track.getInfo()), CommonUtils.formatDuration(millis));
        request.setResetMessage(true);
        return true;
    }
    return false;
}