Android rtsp 播放
时间: 2023-10-09 16:13:29 浏览: 213
Android可以使用MediaPlayer或ExoPlayer来播放rtsp流。
使用MediaPlayer:
1. 创建一个MediaPlayer对象
```java
MediaPlayer mediaPlayer = new MediaPlayer();
```
2. 设置数据源并准备MediaPlayer
```java
mediaPlayer.setDataSource("rtsp://example.com/stream");
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.prepareAsync();
```
3. 在onDestroy中释放MediaPlayer资源
```java
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
```
使用ExoPlayer:
1. 添加依赖
```gradle
implementation 'com.google.android.exoplayer:exoplayer:2.X.X'
```
2. 创建ExoPlayer对象
```java
SimpleExoPlayer player = new SimpleExoPlayer.Builder(context).build();
```
3. 创建MediaSource对象并设置给ExoPlayer
```java
MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse("rtsp://example.com/stream"));
player.setPlayWhenReady(true);
player.prepare(mediaSource);
```
4. 在onDestroy中释放ExoPlayer资源
```java
@Override
protected void onDestroy() {
super.onDestroy();
if (player != null) {
player.release();
player = null;
}
}
```
这样就可以使用MediaPlayer或ExoPlayer在Android上播放rtsp流了。
阅读全文