getDuration正在尝试调用无效的媒体播放器第二次调用媒体播放器时?

时间:2013-07-27 06:14:36

标签: android media-player

下面是我正在使用的代码。我正在使用vimeo视频网址它在我第一次加载活动时工作正常,但在第二次显示消息时调用活动时出现问题尝试在无效的媒体播放器上调用getDuration。

public class VideoActivity extends Activity {

    public LinearLayout main_Lay;
    private TextView textViewPlayed;
    private TextView textViewLength;
    private SeekBar seekBarProgress;
    private SurfaceView surfaceViewFrame;
    private ImageView imageViewPauseIndicator;
    private MediaPlayer player;
    private SurfaceHolder holder;
    private ProgressBar progressBarWait;
    private Timer updateTimer;
    // private Bundle extras;
    private Animation hideMediaController;
    private LinearLayout linearLayoutMediaController;
    private static final String TAG = "androidEx2 = VideoSample";
    public boolean isFullScreen = false;
    private Context m_context;
    public GestureDetector ggg;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.video_layout);
        this.m_context = this;

        main_Lay = (LinearLayout) findViewById(R.id.main_lay);
        main_Lay.startAnimation(AnimationUtils.loadAnimation(this,
            R.anim.slide_out_up));
        surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
        final Button button = (Button) findViewById(R.id.full);
        ggg = new GestureDetector(new OnGestureListener() {

            public boolean onSingleTapUp(MotionEvent arg0) {
                // TODO Auto-generated method stub
                try {
                    if (player != null) {

                        if (player.isPlaying())
                            player.stop();
                        player.reset();

                        player.release();

                        if (updateTimer != null) {
                            updateTimer.cancel();
                        }
                        finish();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    player.reset();
                    player.release();

                    if (updateTimer != null) {
                        updateTimer.cancel();
                    }
                    finish();
                }
                return true;
            }

            public void onShowPress(MotionEvent arg0) {
                // TODO Auto-generated method stub

            }

            public boolean onScroll(MotionEvent arg0, MotionEvent arg1,
                float arg2, float arg3) {
                // TODO Auto-generated method stub
                return false;
            }

            public void onLongPress(MotionEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public boolean onFling(MotionEvent arg0, MotionEvent arg1,
                float arg2, float arg3) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean onDown(MotionEvent arg0) {
                // TODO Auto-generated method stub
                return false;
            }
        });

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
                // TODO Auto-generated method stub
        if (player != null) {
            if (!isFullScreen) {
                isFullScreen = true;
                button.setBackgroundResource(R.drawable.fullscreen_exit_alt);

                        // Get the width of the screen
                int screenWidth = ((Activity) m_context)
                .getWindowManager().getDefaultDisplay()
                .getWidth();
                int screenHeight = ((Activity) m_context)
                .getWindowManager().getDefaultDisplay()
                .getHeight();

                WidthResizeAnimation zoom_out = new WidthResizeAnimation(
                    main_Lay, screenWidth, screenHeight, false);
                zoom_out.setDuration(600);
                zoom_out.setFillAfter(true);

                WidthResizeAnimation zoom_outt = new WidthResizeAnimation(
                    surfaceViewFrame, screenWidth, screenHeight,
                    false);
                zoom_outt.setDuration(600);
                zoom_outt.setFillAfter(true);
                surfaceViewFrame.startAnimation(zoom_outt);
                main_Lay.startAnimation(zoom_out);

            } else {
                isFullScreen = false;
                button.setBackgroundResource(R.drawable.fullscreen_alt);
                int videoWidth = player.getVideoWidth();
                int videoHeight = player.getVideoHeight();
                float videoProportion = (float) videoWidth
                / (float) videoHeight;
                Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: "
                    + videoHeight + " PROP: " + videoProportion);

                        // Get the width of the screen
                int screenWidth = ((Activity) m_context)
                .getWindowManager().getDefaultDisplay()
                .getWidth();
                int screenHeight = ((Activity) m_context)
                .getWindowManager().getDefaultDisplay()
                .getHeight();
                float screenProportion = (float) screenWidth
                / (float) screenHeight;
                Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: "
                    + screenHeight + " PROP: " + screenProportion);

                        // Get the SurfaceView layout
                        // parameters
                android.view.ViewGroup.LayoutParams lp = surfaceViewFrame
                .getLayoutParams();
                android.view.ViewGroup.LayoutParams mainLayoutParam = main_Lay
                .getLayoutParams();

                if (videoProportion > screenProportion) {
                    lp.width = screenWidth;
                    lp.height = (int) ((float) screenWidth / videoProportion);

                    lp.width = (lp.width / 100) * 80;
                    lp.height = (lp.height / 100) * 80;

                } else {
                    lp.width = (int) (videoProportion * (float) screenHeight);
                    lp.height = screenHeight;

                    lp.width = (lp.width / 100) * 70;
                    lp.height = (lp.height / 100) * 70;

                }
                WidthResizeAnimation zoom_in = new WidthResizeAnimation(
                    main_Lay, lp.width, lp.height, false);
                zoom_in.setDuration(600);
                zoom_in.setFillAfter(true);
                        // zoom_in.start();

                WidthResizeAnimation zoom_inn = new WidthResizeAnimation(
                    surfaceViewFrame, lp.width, lp.height, false);
                zoom_inn.setDuration(600);
                zoom_inn.setFillAfter(true);
                        // zoom_in.start();
                surfaceViewFrame.startAnimation(zoom_inn);
                main_Lay.startAnimation(zoom_in);

            }
        }
    }
});
final Button pause = (Button) findViewById(R.id.pause);

pause.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
                // TODO Auto-generated method stub
        if (player != null) {
            if (player.isPlaying()) {
                player.pause();
                pause.setBackgroundResource(R.drawable.play);
                imageViewPauseIndicator.setVisibility(View.GONE);
            } else {
                pause.setBackgroundResource(R.drawable.pause);
                player.start();
                imageViewPauseIndicator.setVisibility(View.GONE);
            }
        }
    }
});

linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
linearLayoutMediaController.setVisibility(View.GONE);

hideMediaController = AnimationUtils.loadAnimation(m_context,
    R.anim.disapearing);
hideMediaController.setAnimationListener(new AnimationListener() {

    @Override
    public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated
                // method stub
        linearLayoutMediaController.setVisibility(View.GONE);
    }

    @Override
    public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated
                // method stub

    }

    @Override
    public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated
                // method stub

    }
});

imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
imageViewPauseIndicator.setVisibility(View.GONE);
if (player != null) {
    if (!player.isPlaying()) {
        imageViewPauseIndicator.setVisibility(View.GONE);
    }
}

textViewPlayed = (TextView) findViewById(R.id.textViewPlayed);
textViewLength = (TextView) findViewById(R.id.textViewLength);

surfaceViewFrame.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
                // TODO Auto-generated
                // method stub
        if (arg0.getId() == R.id.surfaceViewFrame) {
            if (linearLayoutMediaController.getVisibility() == View.GONE) {
                linearLayoutMediaController.setVisibility(View.VISIBLE);
                hideMediaController();
            }
        }
    }
});
surfaceViewFrame.setClickable(false);

seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);
seekBarProgress
.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {
                        // TODO Auto-generated
                        // method stub
        if (player.isPlaying()) {
            progressBarWait.setVisibility(View.VISIBLE);
            player.seekTo(arg0.getProgress() * 1000);
            Log.i(TAG,
                "========== SeekTo : " + arg0.getProgress());
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {
                        // TODO Auto-generated
                        // method stub

    }

    @Override
    public void onProgressChanged(SeekBar seekBar,
        int progress, boolean fromUser) {
        Log.i(TAG, "========== onProgressChanged : " + progress
            + " from user: " + fromUser);
        if (!fromUser) {
            textViewPlayed
            .setText(durationInSecondsToString(progress));
        }
    }
});
seekBarProgress.setProgress(0);

progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);

holder = surfaceViewFrame.getHolder();
holder.addCallback(new Callback() {

    @Override
    public void surfaceDestroyed(SurfaceHolder arg0) {
                // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
                // TODO Auto-generated method stub
        player.setDisplay(holder);
        playVideo();
    }

    @Override
    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
        int arg3) {
                // TODO Auto-generated method stub

    }
});
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

player = new MediaPlayer();
player.setOnPreparedListener(new OnPreparedListener() {

    @Override
    public void onPrepared(MediaPlayer arg0) {
                // TODO Auto-generated method stub
        Log.i(TAG, "========== onPrepared ===========");

        try {
                    int duration = player.getDuration() / 1000; // duration
                                                                // in
                                                                // seconds
                    seekBarProgress.setMax(duration);
                    textViewLength.setText(durationInSecondsToString(duration));
                    progressBarWait.setVisibility(View.GONE);

                    // Get the dimensions of the video
                    int videoWidth = player.getVideoWidth();
                    int videoHeight = player.getVideoHeight();
                    float videoProportion = (float) videoWidth
                    / (float) videoHeight;
                    Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: "
                        + videoHeight + " PROP: " + videoProportion);
                    player.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
                    // Get the width of the screen
                    int screenWidth = ((Activity) m_context).getWindowManager()
                    .getDefaultDisplay().getWidth();
                    int screenHeight = ((Activity) m_context)
                    .getWindowManager().getDefaultDisplay().getHeight();
                    float screenProportion = (float) screenWidth
                    / (float) screenHeight;
                    Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: "
                        + screenHeight + " PROP: " + screenProportion);

                    // Get the SurfaceView layout
                    // parameters
                    android.view.ViewGroup.LayoutParams lp = surfaceViewFrame
                    .getLayoutParams();
                    android.view.ViewGroup.LayoutParams mainLayoutParam = main_Lay
                    .getLayoutParams();

                    if (videoProportion > screenProportion) {
                        lp.width = screenWidth;
                        lp.height = (int) ((float) screenWidth / videoProportion);
                        lp.width = (lp.width / 100) * 80;
                        lp.height = (lp.height / 100) * 80;
                    } else {
                        lp.width = (int) (videoProportion * (float) screenHeight);
                        lp.height = screenHeight;

                        lp.width = (lp.width / 100) * 90;
                        lp.height = (lp.height / 100) * 90;
                    }

                    // Commit the layout parameters
                    surfaceViewFrame.setLayoutParams(lp);
                    RelativeLayout.LayoutParams rr = new RelativeLayout.LayoutParams(
                        lp.width, lp.height);
                    rr.addRule(RelativeLayout.CENTER_IN_PARENT);
                    main_Lay.setLayoutParams(rr);

                    // Start video
                    if (!player.isPlaying()) {
                        player.start();
                        updateMediaProgress();
                        linearLayoutMediaController.setVisibility(View.VISIBLE);
                        hideMediaController();
                    }
                    surfaceViewFrame.setClickable(true);
                } catch (Exception ex) {

                    player.release();
                    finish();
                    ex.printStackTrace();
                }
                ;

            }
        });

player.setOnErrorListener(new OnErrorListener() {

    @Override
    public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
                // TODO Auto-generated method stub
        if (arg0.isPlaying()) {
            arg0.stop();
        }
        arg0.release();
        finish();

        Log.e("Lrapp", "Error code" + arg1);
        return true;
    }
});
player.setOnCompletionListener(new OnCompletionListener() {

    @Override
    public void onCompletion(MediaPlayer arg0) {
                // TODO Auto-generated method stub
        arg0.stop();
        arg0.release();
        if (updateTimer != null) {
            updateTimer.cancel();
        }
        finish();
    }
});
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

    @Override
    public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
                // TODO Auto-generated method stub
        int progress = (int) ((float) arg0.getDuration() * ((float) arg1 / (float) 100));
        seekBarProgress.setSecondaryProgress(progress / 1000);

    }
});
player.setOnSeekCompleteListener(new OnSeekCompleteListener() {

    @Override
    public void onSeekComplete(MediaPlayer arg0) {
                // TODO Auto-generated method stub
        progressBarWait.setVisibility(View.GONE);
    }
});
player.setScreenOnWhilePlaying(true);

}

@Override
public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub

    return ggg.onTouchEvent(event);

}

@Override
public void onBackPressed() {
        // TODO Auto-generated method stub
    super.onBackPressed();

    try {
        if (player != null) {

            if (player.isPlaying())
                player.stop();

            player.release();

            if (updateTimer != null) {
                updateTimer.cancel();
            }
            finish();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        player.release();

        if (updateTimer != null) {
            updateTimer.cancel();
        }
        finish();
    }
}

private void playVideo() {

    new Thread(new Runnable() {
        public void run() {
            try {
                player.setDataSource("video url");
                player.prepareAsync();
            } catch (IllegalArgumentException e) {
                showToast("Error while playing video. Please, check your network connection.");
                Log.i(TAG,
                    "========== IllegalArgumentException ===========");
                e.printStackTrace();
                if (player.isPlaying())
                    player.stop();
                player.release();
                player = null;
                if (updateTimer != null) {
                    updateTimer.cancel();
                }
                finish();
            } catch (IllegalStateException e) {
                showToast("Error while playing video. Please, check your network connection.");
                Log.i(TAG, "========== IllegalStateException ===========");
                e.printStackTrace();
                if (player.isPlaying())
                    player.stop();
                player.release();
                player = null;
                if (updateTimer != null) {
                    updateTimer.cancel();
                }
                finish();
            } catch (IOException e) {
                showToast("Error while playing video. Please, check your network connection.");
                Log.i(TAG, "========== IOException ===========");
                e.printStackTrace();
                if (player.isPlaying())
                    player.stop();
                player.release();
                player = null;
                if (updateTimer != null) {
                    updateTimer.cancel();
                }
                finish();
            }
        }
    }).start();

}

private void showToast(final String string) {
    ((Activity) m_context).runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(m_context, string, Toast.LENGTH_LONG).show();
            ;
        }
    });
}

private void hideMediaController() {
    new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(5000);
                ((Activity) m_context).runOnUiThread(new Runnable() {
                    public void run() {
                        linearLayoutMediaController
                        .startAnimation(hideMediaController);
                    }
                });
            } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }).start();
}

private void updateMediaProgress() {
    updateTimer = new Timer("progress Updater");
    updateTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            ((Activity) m_context).runOnUiThread(new Runnable() {
                public void run() {

                    try {

                        seekBarProgress.setProgress(player
                            .getCurrentPosition() / 1000);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        player.release();
                    }
                }
            });
        }
    }, 0, 1000);
}

public static String durationInSecondsToString(int sec) {
    int hours = sec / 3600;
    int minutes = (sec / 60) - (hours * 60);
    int seconds = sec - (hours * 3600) - (minutes * 60);
    String formatted = String.format("%d:%02d:%02d", hours, minutes,
        seconds);
    return formatted;
}

}

1 个答案:

答案 0 :(得分:1)

第二次打开活动后,会调用曲面回调 - > playVideo() - >球员并不好。 解决方案可以是:
将其插入playVideo()方法:

if (player != null)
{
    player.reset();
} else 
{
    player = new MediaPlayer();
}
//init