android-无法通过MediaPlayer播放视频

时间:2015-03-01 12:42:14

标签: android

这是我的代码:

 MediaPlayer mMediaPlayer;
    SurfaceView mSurfaceView;
    SurfaceHolder holder;
    MediaController mcontroller;
    Handler handler;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firstactivity);

        SurfaceView v = (SurfaceView)findViewById(R.id.surfaceview);
        v.getHolder().addCallback(this);
        handler = new Handler();

mcontroller = new MediaController(this);
        mcontroller.setVisibility(View.INVISIBLE);

        mMediaPlayer = MediaPlayer.create(this, Uri.parse("http://192.168.1.20/uploads/myvid.mp4"));
        // implement a fallback mechanism if it fails, for example if no internet or 404
        if (mMediaPlayer == null) {
            Log.v("this","Faileded to create MediaPlayer");
            return;
        }
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);

        mMediaPlayer.setScreenOnWhilePlaying(true);
        mMediaPlayer.setOnVideoSizeChangedListener(this);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    }
@Override
    public void surfaceCreated(SurfaceHolder arg0) {
        if (mMediaPlayer == null) {
            // implement a fallback mechanism if it fails, for example if no internet or 404
            Log.v("this","MediaPlayer was not created");
            return;
        }

        // the holder reference is already passed as arg0 here
        mMediaPlayer.setDisplay(arg0);
        try {
            // progressDialog.dismiss();
            Log.v("this","start");
            mMediaPlayer.start();

        } catch (IllegalStateException e) {
            Log.v("this",e.getMessage());
            e.printStackTrace();
        }
    }@Override
    public void surfaceDestroyed(SurfaceHolder arg0) {

    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

        // mcontroller.setMediaPlayer(this);
        // mcontroller
        // .setAnchorView(findViewById(R.id.screen_tutorial_video_surface));
        // mcontroller.setEnabled(true);
        //
        // handler.post(new Runnable() {
        // public void run() {
        // mcontroller.show();
        // }
        // });
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    public void start() {
        mMediaPlayer.start();
    }

    public void pause() {
        mMediaPlayer.pause();
    }

    public int getDuration() {
        return mMediaPlayer.getDuration();
    }

    public int getCurrentPosition() {
        return mMediaPlayer.getCurrentPosition();
    }

    public void seekTo(int i) {
        mMediaPlayer.seekTo(1);
    }

    public boolean isPlaying() {
        return mMediaPlayer.isPlaying();
    }

    public int getBufferPercentage() {
        return 0;
    }

    public boolean canPause() {
        return true;
    }

    public boolean canSeekBackward() {
        return true;
    }

    public boolean canSeekForward() {
        return true;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub

    }

电影网址是正确的。在log cat中它表示"未创建MediaPlayer"。此错误来自此surfaceCreated(),有一个条件表明如果mMediaPlayer为null,则显示此错误。

为什么它为空?

我在哪里做错了?

谢谢

1 个答案:

答案 0 :(得分:1)

使用以下

替换所有播放机代码

玩家活动

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.utility.Utils;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.xav.wnPaid.WeatherNationApplicationController.TrackerName;

public class TempVODPlayer extends Activity implements
        OnSeekBarChangeListener, Callback, OnPreparedListener,
        OnCompletionListener, OnBufferingUpdateListener, OnClickListener,
        OnSeekCompleteListener, AnimationListener {
    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";



    String defaulturl="";
    WeatherNationApplicationController application;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.player_activity);

        player = new MediaPlayer();
        seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);


            defaulturl = "Your video url";

        //extras = getIntent().getExtras();
        FrameLayout  videoFrame = (FrameLayout )findViewById(R.id.frameLayoutRoot);
        linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
        linearLayoutMediaController.setVisibility(View.GONE);

        hideMediaController = AnimationUtils.loadAnimation(this,
                R.anim.disapearing);
        hideMediaController.setAnimationListener(this);

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

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

        surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
        surfaceViewFrame.setOnClickListener(this);
        surfaceViewFrame.setClickable(false);


        seekBarProgress.setOnSeekBarChangeListener(this);
        seekBarProgress.setProgress(0);

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

        holder = surfaceViewFrame.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);


        player.setOnPreparedListener(this);
        player.setOnCompletionListener(this);
        player.setOnBufferingUpdateListener(this);
        player.setOnSeekCompleteListener(this);
        player.setScreenOnWhilePlaying(true);

    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        WeatherNationApplicationController.activityResumed();
        super.onResume();
    }
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        WeatherNationApplicationController.activityPaused();
        super.onPause();
    }

    private void playVideo() {
        if (defaulturl.equals("")) {
            showToast("Please, set the video URI in HelloAndroidActivity.java in onClick(View v) method");
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        player.setDataSource(defaulturl);
                        player.prepare();
                    } catch (IllegalArgumentException e) {
                        showToast("Error while playing video");
                        Log.i(TAG,
                                "========== IllegalArgumentException ===========");
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        showToast("Error while playing video");
                        Log.i(TAG,
                                "========== IllegalStateException ===========");
                        e.printStackTrace();
                    } catch (IOException e) {
                        showToast("Error while playing video. Please, check your network connection.");
                        Log.i(TAG, "========== IOException ===========");
                        e.printStackTrace();
                    }
                    catch (Exception e) {
                        // TODO: handle exception
                        Log.i(TAG, "========== eeeeeeee ===========");
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    private void showToast(final String string) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(TempVODPlayer.this, string, Toast.LENGTH_LONG)
                        .show();
                finish();
            }
        });
    }

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

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

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

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (player.isPlaying()) {
            progressBarWait.setVisibility(View.VISIBLE);
            player.seekTo(seekBar.getProgress() * 1000);
            Log.i(TAG, "========== SeekTo : " + seekBar.getProgress());
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        player.setDisplay(holder);
        playVideo();
    }

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

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.i(TAG, "========== onPrepared ===========");
        int duration = mp.getDuration() / 1000; // duration in seconds
        seekBarProgress.setMax(duration);
        textViewLength.setText(Utils.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);

        // Get the width of the screen
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
        int screenHeight = 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();

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

        // Commit the layout parameters
        surfaceViewFrame.setLayoutParams(lp);

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


    @Override
    public void onCompletion(MediaPlayer mp) {
        mp.stop();
        if (updateTimer != null) {
            updateTimer.cancel();
        }
        finish();

        if(player !=null )
        {
            mp.release();
        player.release();
        player = null;
        }

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

    /**
     * Change progress of mediaController
     * */
    private void updateMediaProgress() {
        updateTimer = new Timer("progress Updater");
        updateTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            seekBarProgress.setProgress(player.getCurrentPosition() / 1000);    
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }

                    }
                });
            }
        }, 0, 1000);
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        int progress = (int) (mp.getDuration() * ((float) percent / (float) 100));
        seekBarProgress.setSecondaryProgress(progress / 1000);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.surfaceViewFrame) {
            if (linearLayoutMediaController.getVisibility() == View.GONE) {
                linearLayoutMediaController.setVisibility(View.VISIBLE);
                hideMediaController();
            } else if (player != null) {
                if (player.isPlaying()) {
                    player.pause();
                    imageViewPauseIndicator.setVisibility(View.VISIBLE);
                } else {
                    player.start();
                    imageViewPauseIndicator.setVisibility(View.GONE);
                }
            }
        }
    }

    @Override
    public void onSeekComplete(MediaPlayer mp) {
        progressBarWait.setVisibility(View.GONE);
    }

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

    }

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

    }

    @Override
    public void onAnimationStart(Animation animation) {
        linearLayoutMediaController.setVisibility(View.GONE);
    }
}

Plaeractivity layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/frameLayoutRoot">

        <SurfaceView android:id="@+id/surfaceViewFrame" 
        android:layout_gravity="center" 
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content">
        </SurfaceView>
        <LinearLayout android:layout_width="match_parent"
                 android:id="@+id/linearLayoutMediaController" 
                 android:layout_height="wrap_content" 
                 android:paddingBottom="5dp"
                 android:paddingTop="5dp" 
                 android:layout_gravity="bottom" 
                 android:gravity="center_vertical" 
                 android:background="@color/media_controller_bg_color">
            <TextView android:layout_width="wrap_content" 
                       android:id="@+id/textViewPlayed" 
                       android:layout_marginLeft="5dp" 
                       android:layout_marginRight="5dp"
                       android:textColor="@color/media_controller_text_color" 
                       android:textStyle="bold" android:text="0:00:00" 
                       android:padding="0dp" android:textSize="13sp" 
                       android:gravity="center"
                       android:layout_height="wrap_content">
                       </TextView>
            <SeekBar android:id="@+id/seekBarProgress" 
                  android:layout_weight="1" 
                  style="@style/MyCustomProgressStyle" 
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content" 
                  android:progress="50"></SeekBar>
            <TextView android:layout_width="wrap_content" 
                  android:id="@+id/textViewLength" 
                  android:layout_marginLeft="5dp"
                  android:layout_marginRight="5dp"
                  android:textColor="@color/media_controller_text_color" 
                  android:textStyle="bold" android:text="0:00:00"
                 android:textSize="13sp" android:padding="0dp"
                 android:gravity="center"
                 android:layout_height="wrap_content"></TextView>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ads"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical"
            android:visibility="gone" >

              </LinearLayout>

        <ProgressBar style="?android:attr/progressBarStyleLarge" 
                  android:layout_width="wrap_content"
                   android:layout_height="wrap_content" 
                   android:layout_gravity="center"
                android:id="@+id/progressBarWait"></ProgressBar>
        <ImageView android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:id="@+id/imageViewPauseIndicator" 
            android:layout_gravity="center"
            android:src="@drawable/pause_button"></ImageView>
    </FrameLayout>

</LinearLayout>

可绘制的

中的SeekBarColors.xml选择器
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape>
            <solid android:color="@color/seekbar_bg" />
        </shape>
    </item>
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <solid android:color="@color/seekbar_sec_progress" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="@color/seekbar_progress" />
            </shape>
        </clip>
    </item>
</layer-list>

在color.xml中

<color name="media_controller_text_color">#FFFFFF</color>
    <color name="media_controller_bg_color">#5f5f5f</color>
    <color name="seekbar_bg">#141414</color>
    <color name="seekbar_progress">#a53130</color>
    <color name="seekbar_sec_progress">#875e5e</color>

可绘制的按钮

enter image description here