0

surfaceview と mediaplayer を使用して URL からビデオを再生するアプリを作成します。3つの動画URLを再生したところ、次の動画URLは画像なしで音声のみでした。また、戻るボタンを押してメディアプレーヤーを停止しても、音が残っています。タスクマネージャーでアプリを削除しましたが、音はまだ残っていました。Logcat は以下のバグをスローします:

11-05 09:55:40.340: E/MediaPlayer(5077): 状態 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 に答える