我一直在使用GitHub PierfrancescoSoffrittiandroid-youtube-player。主要代碼使用一個videoID來播放。但是,我想將它用于 YouTube 直播,如果重新創建流,videoId 可以更改。
String videoId = "(ID of YouTube Video)";
youTubePlayer.loadVideo(videoId, 0);
因此,我嘗試使用GitHubVolley向 google YouTube API 發出 http 請求,以獲取直播的最新 videoID。
String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=(MyChannelID)&eventType=live&type=video&key=(MyKey)";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
ytapi.setText("Response: " response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
這將回傳以下內容:
"items": [
{
"kind": "youtube#searchResult",
"etag": "RkUpUQpSKztQlA",
"id": {
"kind": "youtube#video",
"videoId": "GLdex45V_RQ"
目前,我只是在 TextView 中顯示它
final TextView ytapi = view.findViewById(R.id.textYouTubeAPI);
所以我的問題是如何將“videoId”:(在上面回傳的 JSONObject 示例中顯示為“GLdex45V_RQ”)傳遞給 youtubeplayer 的 loadVideo() 方法。我假設我需要決議 videoId 結果的 JSONObject 并傳遞它,但這就是我被卡住的地方。
String videoId = "(videoid from JSONObject)";
youTubePlayer.loadVideo(videoId, 0);
我已經嘗試過類似的東西
String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=(MyChannelID)&eventType=live&type=video&key=(MyKey)";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i ) {
JSONObject id = jsonArray.getJSONObject(i);
String VideoID = id.getString("videoId");
ytapi.setText(VideoID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
mQueue.add(request);
但是在 com.android.volley.Request 上獲取空物件參考
最終使用 Volley、Google YouTube API 和 JSON Response 回傳 youtube 直播視頻 ID 的方法。
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i ) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
JSONObject jsonArray1 = jsonObject.getJSONObject("id");
String videoid = jsonArray1.optString("videoId");
ytapi.setText(videoid);
}
} catch (JSONException e) {
e.printStackTrace();
}
uj5u.com熱心網友回復:
我的解決方案缺少陣列。
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i ) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
JSONObject jsonArray1 = jsonObject.getJSONObject("id");
String videoid = jsonArray1.optString("videoId");
ytapi.setText(videoid);
}
} catch (JSONException e) {
e.printStackTrace();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/327503.html
上一篇:如何獲得多個Spinner值?
