获取channelId对应直播videoId适配PierfrancescoSoffritti YouTube播放器
实现方案
前置准备
提前申请好YouTube Data API的调用密钥,确认要加载的频道ID正确可用。
第一步:添加必要依赖和权限
在模块级build.gradle中添加网络请求和JSON解析依赖:
dependencies { // 网络请求组件,也可替换为项目已在用的Retrofit等框架 implementation 'com.squareup.okhttp3:okhttp:4.11.0' // JSON解析组件 implementation 'com.google.code.gson:gson:2.10.1' }
在AndroidManifest.xml中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
第二步:封装直播videoId查询逻辑
先定义请求结果回调接口:
public interface OnLiveVideoIdFetchListener { void onSuccess(String videoId); void onFailure(Exception e); }
封装API请求方法:
private void fetchLiveVideoId(String channelId, String apiKey, OnLiveVideoIdFetchListener listener) { OkHttpClient client = new OkHttpClient(); String requestUrl = String.format("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=%s&eventType=live&type=video&key=%s", channelId, apiKey); Request request = new Request.Builder() .url(requestUrl) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { listener.onFailure(e); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { if (!response.isSuccessful()) { listener.onFailure(new Exception("请求错误,状态码:" + response.code())); return; } String responseBody = response.body().string(); try { JsonObject resultJson = new Gson().fromJson(responseBody, JsonObject.class); JsonArray liveItems = resultJson.getAsJsonArray("items"); if (liveItems.isEmpty()) { listener.onFailure(new Exception("当前频道暂无正在播出的直播")); return; } // 取第一条直播的videoId String videoId = liveItems.get(0).getAsJsonObject() .getAsJsonObject("id") .get("videoId") .getAsString(); listener.onSuccess(videoId); } catch (Exception parseException) { listener.onFailure(parseException); } } }); }
第三步:修改播放器回调逻辑
注意网络请求在子线程完成,拿到videoId后需要切回主线程操作播放器:
youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() { @Override public void onReady(@NonNull YouTubePlayer youTubePlayer) { // 替换为实际的频道ID和你的API密钥 String channelId = "你的目标频道ID"; String apiKey = "你的YouTube Data API密钥"; fetchLiveVideoId(channelId, apiKey, new OnLiveVideoIdFetchListener() { @Override public void onSuccess(String videoId) { // 切回主线程加载直播 runOnUiThread(() -> youTubePlayer.loadVideo(videoId, 0)); } @Override public void onFailure(Exception e) { // 自定义错误处理,比如提示用户暂无直播 runOnUiThread(() -> Toast.makeText(YourActivity.this, "加载失败:"+e.getMessage(), Toast.LENGTH_SHORT).show()); } }); } });
注意事项
- 如果代码写在Fragment中,
runOnUiThread需要替换为requireActivity().runOnUiThread - YouTube Data API有调用配额限制,上线前请根据业务量级评估配额是否足够,可添加短时间缓存减少重复请求
- 如果需要支持直播中断重推后自动恢复播放,可添加定时轮询逻辑,定期校验当前播放的videoId是否有效
内容的提问来源于stack exchange,提问作者BinDev
相关产品推荐
相关产品推荐

