0

我编写了一个应用程序来使用 Surfaceview 和 mediaplayer 从 Url 播放视频。当我播放 3 个视频 url 时,下一个视频 url 只有声音没有图像。当我按下后退按钮停止媒体播放器时,声音仍然存在。我通过任务管理器删除了应用程序,但声音仍然存在。Logcat 在下面抛出错误:

11-05 09:55:40.340: E/MediaPlayer(5077): stop 在状态 0 中调用

11-05 09:55:40.340: E/MediaPlayer(5077): 错误 (-38, 0)

我的代码:

public class ChannelDetailActivity extends FragmentActivity {

    public static final String CHANNEL_ID = "channelid";
    private int channel_id;
    private TextView ab_title;
    private TextView mStartTime;
    private TextView mEndTime;
    private ImageView mPlayBtn;
//  private ProgressBar progress_loading;
    public String Urltoken;
    public String Urlvideo;
    private String userToken;
    private Utilities utils;
    private ViewPager mViewPager;
    private PagerAdapter mPagerAdapter;
    private RadioGroup rdgVideoBtn;
    private TappableSurfaceView mSurfaceView;
    private RelativeLayout mBottomController;
    private Animation mAnimFadeOut;
    private RelativeLayout comment_container;
    private VideoView vd;
    private Handler mHandler = new Handler();
    /*
     * Switch screen between portrait and landscape
     */
    private OnClickListener mOnFullScreenBtnListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Display display = ((WindowManager)getSystemService(WINDOW_SERVICE))
                    .getDefaultDisplay();
            int orientation = display.getRotation();
            switch (orientation) {
            case Surface.ROTATION_0:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                break;
            case Surface.ROTATION_90:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
            }
        }
    };
    protected OnErrorListener mOnErrorListener = new OnErrorListener() {

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            mHandler.removeCallbacksAndMessages(mUpdateTimeTask);
            return false;
        }
    };
    /*
     * runnerable to display time on video
     */
    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            long totalDuration = mMediaPlayer.getDuration();
            long currentDuration = mMediaPlayer.getCurrentPosition();

            if (totalDuration == 0 && !mEndTime.getText().equals("LIVE")) {
                mEndTime.setText("LIVE");
            }
            if (currentDuration > 0) {
                progress_loading.setVisibility(View.GONE);
            }
            mStartTime.setText("" + utils.milliSecondsToTimer(currentDuration));

            mHandler.postDelayed(this, 100);

        }
    };
    private MediaPlayer.OnPreparedListener mOnPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mPlayBtn.setOnClickListener(OnPlayBtnListener);
            mMediaPlayer.start();
            mHandler.postDelayed(mUpdateTimeTask, 100);
        }
    };
    /*
     * click to play video
     */
    private OnClickListener OnPlayBtnListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mMediaPlayer == null) {
                mPlayBtn.setOnClickListener(null);
                playVideo(videoUrl);
                return;
            }
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
                mPlayBtn.setImageResource(R.drawable.ic_media_play);
            } else {
                mMediaPlayer.start();
                mPlayBtn.setImageResource(android.R.drawable.ic_media_pause);
            }

        }
    };
    protected boolean isShowController;
    /*
     * an hien mediacontroller khi an vao man hinh player
     */
    private TapListener onTouchListener = new TapListener() {

        @Override
        public void onTap(MotionEvent event) {
            if (!isShowController) {
                mBottomController.setVisibility(View.VISIBLE);
                mHandler.postDelayed(mHideMediaController, 3000);
            }
        }
    };
    protected MediaPlayer mMediaPlayer;
    private Callback mSurfaceHolderCallback = new Callback() {
        @Override
        public void surfaceChanged(SurfaceHolder surfaceholder, int arg1,
                int arg2, int arg3) {
            mSurfaceHolder = surfaceholder;
            if (mMediaPlayer != null) {
                mMediaPlayer.setDisplay(surfaceholder);
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder arg0) {
            Log.d("surfaceCreated", "surfaceCreated");

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder arg0) {
            Log.d("surfaceDestroyed", "surfaceDestroyed");

        }
    };
    private ProgressBar progress_loading;
    private ImageView mFullScreenBtn;
    private SurfaceHolder mSurfaceHolder;
    private RelativeLayout RLpager;
    private int width_pager,height_pager;
    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_channel_detail_fix);
        Bundle extras = getIntent().getExtras();
        userToken = ((GlobalApp) getApplication()).getUserToken();
        utils = new Utilities();
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getActionBar().setCustomView(R.layout.ab_detail_custom);
        RLpager = (RelativeLayout) findViewById(R.id.comment_container);
        width_pager = getWindowManager().getDefaultDisplay().getWidth();
        height_pager = getWindowManager().getDefaultDisplay().getHeight();
        ab_title = (TextView) findViewById(R.id.tv_ab_title);
        if (extras != null) {
            channel_id = extras.getInt(ChannelDetailActivity.CHANNEL_ID);
        }
        mViewPager = (ViewPager) findViewById(R.id.vp_channel_detail);
        mViewPager.setOnPageChangeListener(mOnViewPagerChangeListener);
        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this,
                EPGByChannelFragment.class.getName(), extras));
        fragments.add(Fragment.instantiate(this,
                ChannelCommentFragment.class.getName(), extras));
        mPagerAdapter = new PagerAdapter(getSupportFragmentManager(), fragments);
        mViewPager.setAdapter(mPagerAdapter);
        comment_container = (RelativeLayout) findViewById(R.id.comment_container);
        rdgVideoBtn = (RadioGroup) findViewById(R.id.rg_video_btn);
        rdgVideoBtn.setOnCheckedChangeListener(mRadioGroupVideoListener);
        mSurfaceView = (TappableSurfaceView) findViewById(R.id.surface_view);
        mSurfaceView.addTapListener(onTouchListener);
        mStartTime = (TextView) findViewById(R.id.tv_video_start_time);
        mEndTime = (TextView) findViewById(R.id.tv_video_end_time);
        mPlayBtn = (ImageView) findViewById(R.id.iv_video_play);
        progress_loading = (ProgressBar) findViewById(R.id.player_progress);
        mFullScreenBtn = (ImageView) findViewById(R.id.iv_video_small_zoom);
        mFullScreenBtn.setOnClickListener(mOnFullScreenBtnListener);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(mSurfaceHolderCallback);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mBottomController = (RelativeLayout) findViewById(R.id.bottom_info);
        mAnimFadeOut = AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out);
    }
    @Override
    protected void onStart() {
        super.onStart();
        getChannelInfo();
    }
    protected String videoUrl;
    private void getChannelInfo() {
        TimeTVApiCaller.getInstance().getChannel(channel_id, this,
                new AjaxCallback<ChannelInfo>() {
                    @Override
                    public void callback(String url, ChannelInfo object,
                            AjaxStatus status) {
                        if (object != null) {
                            videoUrl = object.getChannelUrls().get(0).getPath();
                            mPlayBtn.setOnClickListener(OnPlayBtnListener);
                            ab_title.setText(object.getName());
                            /*
                             * Auto play video
                             */
                            playVideo(videoUrl);
                        }
                    }
                });
    }
    protected void playVideo(String url) {
        mHandler.postDelayed(mHideMediaController, 3000);
        mPlayBtn.setImageResource(android.R.drawable.ic_media_pause);
        progress_loading.setVisibility(View.VISIBLE);
        TimeTVApiCaller.getInstance().getChannelStream(url, this,
                new AjaxCallback<String>() {
                    @Override
                    public void callback(String url, String object,
                            AjaxStatus status) {
                        String path_stream = object.replace("\"", "");
                        mMediaPlayer = new MediaPlayer();
                        mMediaPlayer.setOnPreparedListener(mOnPreparedListener);
                        mMediaPlayer.setOnErrorListener(mOnErrorListener);
                        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                // TODO Auto-generated method stuber
                                mMediaPlayer.stop();
                            }
                        });
                        try {
                            mMediaPlayer.setDataSource(path_stream);
                            mSurfaceView.setDrawingCacheEnabled(true);
                            mSurfaceView.setDrawingCacheQuality(SurfaceView.DRAWING_CACHE_QUALITY_HIGH);
                            mSurfaceView.setDrawingCacheBackgroundColor(Color.BLACK);
                            mSurfaceView.setDuplicateParentStateEnabled(true);
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mMediaPlayer.setDisplay(mSurfaceHolder);
                        mMediaPlayer
                                .setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mMediaPlayer.setScreenOnWhilePlaying(true);
                        mMediaPlayer.prepareAsync();
                        mMediaPlayer.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {

                            @Override
                            public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                                // TODO Auto-generated method stub
                                int width_SurfaceView = mSurfaceView.getWidth();
                                int height_SurfaceView = mSurfaceView.getHeight();
                                float boxWidth = width_SurfaceView;
                                float boxHeight = height_SurfaceView;
                                float videoWidth = mMediaPlayer.getVideoWidth();
                                float videoHeight = mMediaPlayer.getVideoHeight();
                                float wr = boxWidth/videoWidth;
                                float hr = boxHeight/videoHeight;
                                float ar = videoWidth/videoHeight;
                                if(wr > hr) width_SurfaceView = (int) (boxHeight * ar);
                                else height_SurfaceView = (int) (boxWidth / ar);
                                if(mMediaPlayer.isPlaying()){
                                    mSurfaceHolder.setFixedSize(width_SurfaceView, height_SurfaceView);
                                }
                            }
                        });
                    }
                });
    }

    TextView tv;


       @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
           Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
           int orientation = display.getRotation();
            if((event.getAction()== KeyEvent.ACTION_DOWN)&&(keyCode == KeyEvent.KEYCODE_BACK))
            {
                if(orientation == Surface.ROTATION_0)
                {
                    if(mMediaPlayer != null && mMediaPlayer.isPlaying())
                    {
                        mMediaPlayer.stop();
                        mMediaPlayer.setVolume(0, 0);
                    }
                    finish();
                    return true;
                }
                else
                {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    return false;
                }
            }

            return super.onKeyDown(keyCode, event);
        }
        /*
         * switch to full screen when configuration changed
         * 
         * @see
         * android.support.v4.app.FragmentActivity#onConfigurationChanged(android
         * .content.res.Configuration)
         */
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().clearFlags(
                        WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getActionBar().hide();
                comment_container.setVisibility(View.GONE);
            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                getWindow().addFlags(
                        WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getActionBar().show();
                comment_container.setVisibility(View.VISIBLE);
            }
        }
    private Runnable mHideMediaController = new Runnable() {

        @Override
        public void run() {
            mBottomController.startAnimation(mAnimFadeOut);
            mBottomController.setVisibility(View.INVISIBLE);
            isShowController = false;
            mHandler.removeCallbacks(mHideMediaController);
        }
    };
    @Override
    protected void onPause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying())
            mMediaPlayer.pause();
        super.onPause();

    }
    @Override
    protected void onStop() {
        if(mMediaPlayer != null && mMediaPlayer.isPlaying())
        {
            mMediaPlayer.setVolume(0, 0);
            mMediaPlayer.stop();
            mMediaPlayer.setAudioStreamType(RESULT_CANCELED);
        }
        finish();
        super.onStop();
    };
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

}

你能帮我修理它们吗?

4

1 回答 1

0

该错误会告诉您您需要知道的一切。您在 MediaPlayer 空闲时调用 stop()。

在 PC 而不是我的手机上查看您的代码后,我很确定问题在于您调用stop()OnCompletionListener. 这是完全没有必要的,因为媒体在进入回调时已经停止了。事实上,调用stop()会首先调用该回调。

您应该能够使用 logcat 来查明代码中发生错误的确切行。如果您发布该信息并指出将来错误指的是哪一行,这将很有帮助。

于 2013-11-05T11:37:07.860 回答