How To Download Youtube Videos In Java
java-youtube-downloader
Unproblematic java parser for retrieving youtube video metadata.
Library is not stable, because Youtube frequently changes web structure of its pages. I don't use this library regularly to discover the errors. Thats why errors are stock-still as soon as someone finds information technology and opens an outcome. Feel gratis to report an fault or sumbit a PR.
Warning: Youtube API does not back up a video download. In fact, information technology is prohibited - Terms of Service - 2. Prohibitions.
Alarm: Downloading videos may violate copyrights!
This project is simply for educational purposes. I urge not to utilise this project to violate any laws.
Usage
Configuration
// init downloader with default config YoutubeDownloader downloader = new YoutubeDownloader(); // or with custom config Config config = new Config.Builder() .executorService(executorService) // for async requests, default Executors.newCachedThreadPool() .maxRetries(1) // retry on failure, default 0 .header("Take-language", "en-US,en;") // extra request header .proxy("192.168.0.1", 2005) .proxyCredentialsManager(proxyCredentials) // default ProxyCredentialsImpl .proxy("192.168.0.1", 2005, "login", "pass") .build(); YoutubeDownloader downloader = new YoutubeDownloader(config); // or configure after init Config config = downloader.getConfig(); config.setMaxRetries(0); Asking
// each asking accepts optional params that will override global configuration Request request = new Request(...) .maxRetries(...) .proxy(...) .header(...) .callback(...) // add callback for async processing .async(); // brand request async Response
Response<T> response = downloader.get...(request) // go response condition one of [downloading, completed, canceled, error] ResponseStatus status = response.status(); // become reponse data // NOTE: will block current thread until completion if request is async T data = response.information(); // or become with timeout, may throw TimeoutException T information = response.data(i, TimeUnit.SECONDS); // cancel if request is async boolean canceled = response.cancel(); // get response error if request finished exceptionally // Notation: will cake current thread until completion if request is async Throwable fault = response.error(); // check if asking finished successfully // NOTE: volition block current thread until completion if asking is async boolean ok = response.ok(); VideoInfo
String videoId = "abc12345"; // for url https://world wide web.youtube.com/watch?v=abc12345 // sync parsing RequestVideoInfo request = new RequestVideoInfo(videoId); Response<VideoInfo> response = downloader.getVideoInfo(request); VideoInfo video = response.data(); // async parsing RequestVideoInfo asking = new RequestVideoInfo(videoId) .callback(new YoutubeCallback<VideoInfo>() { @ Override public void onFinished(VideoInfo videoInfo) { System.out.println("Finished parsing"); } @ Override public void onError(Throwable throwable) { Arrangement.out.println("Error: " + throwable.getMessage()); } }) .async(); Response<VideoInfo> response = downloader.getVideoInfo(asking); VideoInfo video = response.data(); // volition block thread // video details VideoDetails details = video.details(); Organisation.out.println(details.championship()); System.out.println(details.viewCount()); details.thumbnails().forEach(image -> System.out.println("Thumbnail: " + paradigm)); // HLS url only for live videos and streams if (video.details().isLive()) { System.out.println("Live Stream HLS URL: " + video.details().liveUrl()); } // go videos formats only with audio List<VideoWithAudioFormat> videoWithAudioFormats = video.videoWithAudioFormats(); videoWithAudioFormats.forEach(information technology -> { Organization.out.println(it.audioQuality() + ", " + information technology.videoQuality() + " : " + it.url()); }); // get all videos formats (may contain ameliorate quality but without sound) List<VideoFormat> videoFormats = video.videoFormats(); videoFormats.forEach(it -> { System.out.println(it.videoQuality() + " : " + it.url()); }); // become audio formats Listing<AudioFormat> audioFormats = video.audioFormats(); audioFormats.forEach(information technology -> { Organisation.out.println(it.audioQuality() + " : " + it.url()); }); // get best format video.bestVideoWithAudioFormat(); video.bestVideoFormat(); video.bestAudioFormat(); // filtering formats List<Format> formats = video.findFormats(new Filter<Format>() { @ Override public boolean test(Format format) { return format.extension() == Extension.WEBM; } }); // itags can be found here - https://gist.github.com/sidneys/7095afe4da4ae58694d128b1034e01e2 Format formatByItag = video.findFormatByItag(18); // return null if not constitute if (formatByItag != cypher) { Arrangement.out.println(formatByItag.url()); }
Downloading video
File outputDir = new File("my_videos"); Format format = videoFormats.get(0); // sync downloading RequestVideoFileDownload request = new RequestVideoFileDownload(format) // optional params .saveTo(outputDir) // by default "videos" directory .renameTo("video") // by default file name will be same as video title on youtube .overwriteIfExists(true); // if false and file with such name already exits sufix will be added video(1).mp4 Response<File> response = downloader.downloadVideoFile(request); File information = response.information(); // async downloading with callback RequestVideoFileDownload asking = new RequestVideoFileDownload(format) .callback(new YoutubeProgressCallback<File>() { @ Override public void onDownloading(int progress) { System.out.printf("Downloaded %d%%\due north", progress); } @ Override public void onFinished(File videoInfo) { System.out.println("Finished file: " + videoInfo); } @ Override public void onError(Throwable throwable) { System.out.println("Fault: " + throwable.getLocalizedMessage()); } }) .async(); Response<File> response = downloader.downloadVideoFile(request); File data = response.data(); // will cake current thread // async downloading without callback RequestVideoFileDownload request = new RequestVideoFileDownload(format).async(); Response<File> response = downloader.downloadVideoFile(request); File data = response.data(twenty, TimeUnit.SECONDS); // will block current thread and may throw TimeoutExeption // download in-retention to OutputStream OutputStream bone = new ByteArrayOutputStream(); RequestVideoStreamDownload request = new RequestVideoStreamDownload(format, os); Response<Void> response = downloader.downloadVideoStream(asking);
Subtitles
// you can get subtitles from video captions if y'all have already parsed video info Listing<SubtitlesInfo> subtitlesInfo = video.subtitles(); // Annotation: includes auto-generated // if you don't demand video info, but just subtitles make this request instead Response<List<SubtitlesInfo>> response = downloader.getSubtitlesInfo(new RequestSubtitlesInfo(videoId)); // NOTE: does not include auto-generated List<SubtitlesInfo> subtitlesInfo = response.data(); for (SubtitlesInfo info : subtitles) { RequestSubtitlesDownload asking = new RequestSubtitlesDownload(info) // optional .formatTo(Extension.JSON3) .translateTo("great britain"); // sync download Response<String> response = downloader.downloadSubtitle(asking); String subtitlesString = response.data(); // async download RequestSubtitlesDownload asking = new RequestSubtitlesDownload(info) .callback(...) // optional .async(); Response<String> response = downloader.downloadSubtitle(request); String subtitlesString = response.information(); // volition block current thread // to download using external download manager Cord downloadUrl = asking.getDownloadUrl(); } Playlists
Cord playlistId = "abc12345"; // for url https://www.youtube.com/playlist?listing=abc12345 RequestPlaylistInfo request = new RequestPlaylistInfo(playlistId); Response<PlaylistInfo> response = downloader.getPlaylistInfo(request); PlaylistInfo playlistInfo = response.data(); // playlist details PlaylistDetails details = playlistInfo.details(); System.out.println(details.championship()); Arrangement.out.println(details.videoCount()); // get video details PlaylistVideoDetails videoDetails = playlistInfo.videos().become(0); System.out.println(videoDetails.videoId()); System.out.println(videoDetails.title()); Organisation.out.println(videoDetails.index()); Aqueduct uploads
String channelId = "abc12345"; // for url https://www.youtube.com/channel/abc12345 // or String channelId = "someName"; // for url https://www.youtube.com/c/someName RequestChannelUploads asking = new RequestChannelUploads(channelId); Response<PlaylistInfo> response = downloader.getChannelUploads(request); PlaylistInfo playlistInfo = response.data();
Search
RequestSearchResult request = new RequestSearchResult("search query") // filters .type(TypeField.VIDEO) // Videos only .format(FormatField._3D, FormatField.HD) // 3D Hd videos .match(FeatureField.SUBTITLES) // with subtitles .during(DurationField.OVER_20_MINUTES) // more than 20 minutes videos .uploadedThis(UploadDateField.Month) // uploaded this month // other parameters .forceExactQuery(true) // avoid automobile correction .sortBy(SortField.VIEW_COUNT); // results sorted past view count // or RequestSearchResult request = new RequestSearchResult("search query") .filter( TypeField.VIDEO, FormatField.Hard disk drive, (...) UploadDateField.Month); SearchResult result = downloader.search(asking).information(); // recollect side by side consequence (20 items max per continuation) if (outcome.hasContinuation()) { RequestSearchContinuation nextRequest = new RequestSearchContinuation(result); SearchResult continuation = downloader.searchContinuation(nextRequest).information(); } // a query is suggested, become its result if (result.suggestion() != null) { Organization.out.println(result.proposition().query()); // suggested query RequestSearchable suggestedRequest = new RequestSearchable(issue.suggestion()); SearchResult suggestedResult = downloader.search(suggestedRequest).data(); } // query refinements if (effect.refinements() != null) { Organisation.out.println(result.refinements().get(0).query()); // refinement query RequestSearchable refinedRequest = new RequestSearchable(consequence.refinements().get(0)); SearchResult refinedResult = downloader.search(refinedRequest).information(); } // the query has been automobile corrected, force original query if (effect.isAutoCorrected()) { System.out.println(result.autoCorrectedQuery()); // corrected query SearchResult forcedResult = downloader.search(request.forceExactQuery(true)).data(); } // details System.out.println(result.estimatedResults()); // items, 20 max per result (+ possible shelves on first upshot) List<SearchResultItem> items = upshot.items(); List<SearchResultVideoDetails> videos = result.videos(); List<SearchResultChannelDetails> channels = result.channels(); List<SearchResultPlaylistDetails> playlists = upshot.playlists(); List<SearchResultShelf> shelves = upshot.shelves(); // detail cast SearchResultItem particular = items.get(0); switch (detail.type()) { case VIDEO: System.out.println(item.asVideo().description()); pause; example SHELF: for (SearchResultVideoDetails video : item.asShelf().videos()) { System.out.println(video.writer()); } interruption; (...) } // Base of operations 64 (optional) : apply another base 64 encoder for search parameters // Archetype JDK and Android API >= 26 Base64Encoder.setInstance(bytes -> Base64.getUrlEncoder().encodeToString(bytes)); // Android API < 26 Base64Encoder.setInstance(new Base64Encoder() { @ Override public String encodeToString(byte[] bytes) { return Base64.encodeToString(bytes, Base64.URL_SAFE); } }; Include
Maven
<repositories> <repository> <id>jitpack.io</id> <url>https://jitpack.io</url> </repository> </repositories>
<dependency> <groupId>com.github.sealedtx</groupId> <artifactId>java-youtube-downloader</artifactId> <version>3.1.0</version> </dependency> Gradle
allprojects { repositories { ... maven { url 'https://jitpack.io' } } } dependencies { implementation 'com.github.sealedtx:java-youtube-downloader:3.ane.0' } Android
android { ... compileOptions { sourceCompatibility JavaVersion . VERSION_1_8 targetCompatibility JavaVersion . VERSION_1_8 } // For Kotlin projects kotlinOptions { jvmTarget = "1.viii" } } How To Download Youtube Videos In Java,
Source: https://github.com/sealedtx/java-youtube-downloader
Posted by: pucciospirly98.blogspot.com

0 Response to "How To Download Youtube Videos In Java"
Post a Comment