Example using MediaPlayer/SurfaceView example to play video from Internet.
MainActivity.java
package com.blogspot.android_er.androidmediaplayer;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity
implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener {
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private MediaPlayer mediaPlayer;
String videoSource =
"https://sites.google.com/site/androidexample9/download/RunningClock.mp4";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Toast.makeText(MainActivity.this,
"surfaceCreated()", Toast.LENGTH_LONG).show();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(this);
try {
mediaPlayer.setDataSource(videoSource);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,
"something wrong!\n" + e.toString(),
Toast.LENGTH_LONG).show();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
Toast.makeText(MainActivity.this,
"onPrepared()", Toast.LENGTH_LONG).show();
}
}
layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical"
tools:context="com.blogspot.android_er.androidmediaplayer.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<SurfaceView
android:id="@+id/surfaceview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
uses-permission of "android.permission.INTERNET" is needed in AndroidManifest.xml.
Next:
- Add MediaController to MediaPlayer
Related:
- VideoView example to play video from Internet
No comments:
Post a Comment