我正在使用YouTube API在我的应用中播放视频。
我想在用户输入片段时播放视频,因此我使用命令player.play();
自动播放。但是这个命令似乎不起作用......
这是我的代码:
public class YouTubeVideoFragment extends YouTubePlayerFragment{
YouTubePlayer player;
public YouTubeVideoFragment()
{
}
@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
if(player!= null)
{
player.release();
}
}
@Override
public void onStop()
{
// TODO Auto-generated method stub
super.onStop();
if(player!= null)
{
player.release();
}
}
public static YouTubeVideoFragment newInstance(String url)
{
YouTubeVideoFragment f = new YouTubeVideoFragment();
Bundle b = new Bundle();
b.putString("url", url);
f.setArguments(b);
f.init();
return f;
}
private void init()
{
initialize("api_key", new OnInitializedListener() {
@Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1)
{
Log.e("YouTubeFragment", "Error");
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored)
{
if (!wasRestored)
{
player.cueVideo(getArguments().getString("url"));
player.play();//THIS DOESNT WORK!!!
}
}
});
}
}
答案 0 :(得分:4)
如果您需要在片段初始化后立即加载和播放视频,则只需使用player.loadVideo(videoId)
代替player.cueVideo(videoId)
并覆盖onLoaded()
挂钩。
查看文档:
loadVideo(String videoId) 加载并播放指定的视频。
cueVideo(String videoId) 加载指定视频的缩略图并准备播放器播放视频,但在调用play()之前不会下载任何视频流。
答案 1 :(得分:0)
你必须在PlayerStateChangeListener()的onLoaded()中调用player.play()。 因此,将onInitializationSuccess更改为:
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored)
{
if (!wasRestored)
{
player.setPlayerStateChangeListener(new PlayerStateChangeListener() {
@Override
public void onVideoStarted() {
}
@Override
public void onVideoEnded() {
}
@Override
public void onLoading() {
}
@Override
public void onLoaded(String videoId) {
player.play();
}
@Override
public void onError(ErrorReason reason) {
}
@Override
public void onAdStarted() {
}
});
}