使用多线程将多个视频插入播放列表会导致视频丢失



当我连续插入视频时,所有视频都会插入到播放列表中,但这需要很长时间。当我使用多线程时,最终有一半以上的视频丢失了。如何在不丢失任何视频的情况下快速插入多个视频?

// Insert videos. 5 videos per asyncTask
List<List<YTVideo>> chunks = Lists.partition(videos, 5);
for (int i = 0; i < chunks.size(); i++) {
    videoAndPlaylistContainer container = new videoAndPlaylistContainer();
    container.playlistId = playlistId;
    List<YTVideo> chunk = chunks.get(i);
    container.videos = chunk;
    InsertPlayListItemTask insertPlaylistItemsTask = new InsertPlayListItemTask();
    runningTasks.add(insertPlaylistItemsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,container));
}

.

 private class InsertPlayListItemTask extends AsyncTask<videoAndPlaylistContainer, Void, Void>{
        @Override
        protected Void doInBackground(videoAndPlaylistContainer... params) {
            videoAndPlaylistContainer container = params[0];
            List<YTVideo> videosChunk = container.videos;
            String playlistId = container.playlistId;
            for (int i = 0; i < videosChunk.size(); i++) {
                YTVideo video = videosChunk.get(i);
                String videoId = video.getId();
                long pos = video.getPosition();
                try {
                    ResourceId resourceId = new ResourceId();
                    resourceId.setKind("youtube#video");
                    resourceId.setVideoId(videoId);
                    PlaylistItemSnippet playlistItemSnippet = new PlaylistItemSnippet();
                    // playlistItemSnippet.setTitle("First video in the test playlist");
                    playlistItemSnippet.setPlaylistId(playlistId);
                    playlistItemSnippet.setResourceId(resourceId);
                    playlistItemSnippet.setPosition(pos);
                    PlaylistItem playlistItem = new PlaylistItem();
                    playlistItem.setSnippet(playlistItemSnippet);

                    YouTube.PlaylistItems.Insert playlistItemsInsertCommand =
                            youtube.playlistItems().insert("snippet", playlistItem);
                    playlistItemsInsertCommand.execute();
                    System.out.println("Inserted video: " + video);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

编辑:videos.size(( 到 chunks.size((。删除了插入的计数++;

这行看起来不对...

for (int i = 0; i < videos.size(); i++) {

i变量将根据videos集合的大小而增长,但您只能在此处使用 i 变量访问chunks集合中的元素...

List<YTVideo> chunk = chunks.get(i);

我无法想象为什么你(最终(没有得到ArrayIndexOutOfBounds的异常,除了也许你正在用少于 5 个视频测试你的代码(到目前为止(。

相关内容

  • 没有找到相关文章

最新更新