项目中用到在播放服务上的m3u8的视频,android自带的MediaPlayer就支持,因此写个demo记录下 布局文件activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="300dp" />
</LinearLayout>
Activity
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private String url = "http://121.132.117.216/hls/a.m3u8";
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_my_media_player);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(url);
surfaceHolder =surfaceView.getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
mediaPlayer.setDisplay(surfaceHolder);
}
@Override
public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
}
});
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
mediaPlayer.setLooping(true);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
不过在模拟器上播放时只有声音没有画面,在真机上有声音和画面
|