IjkMediaPlayer.setDataSource播放raw文件夹内文件
时间: 2023-10-24 09:26:05 浏览: 160
android应用播放raw文件中的音乐
5星 · 资源好评率100%
你可以使用以下代码来使用IjkMediaPlayer播放raw文件夹内的文件:
```java
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import java.io.IOException;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener {
private SurfaceView mSurfaceView;
private IjkMediaPlayer mMediaPlayer;
private SurfaceHolder mSurfaceHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化IjkMediaPlayer
IjkMediaPlayer.loadLibrariesOnce(null);
IjkMediaPlayer.native_profileBegin("libijkplayer.so");
mSurfaceView = findViewById(R.id.surface_view);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// 设置MediaPlayer
mMediaPlayer = new IjkMediaPlayer();
mMediaPlayer.setDisplay(mSurfaceHolder);
// 获取音频焦点
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
// 播放raw文件夹内的文件
Resources resources = getResources();
AssetFileDescriptor afd = resources.openRawResourceFd(R.raw.test);
try {
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IOException e) {
e.printStackTrace();
}
// 准备播放
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// 释放MediaPlayer
mMediaPlayer.release();
mMediaPlayer = null;
}
@Override
public void onPrepared(MediaPlayer mp) {
// 开始播放
mMediaPlayer.start();
}
}
```
注意,这里使用了IjkMediaPlayer而不是Android自带的MediaPlayer,因为IjkMediaPlayer支持更多的视频格式,并且在播放过程中能够实时调整画面大小和速度等参数。同时,需要在项目的build.gradle文件中添加以下依赖:
```groovy
dependencies {
implementation 'tv.danmaku.ijk.media:ijkplayer-java:0.8.8'
implementation 'tv.danmaku.ijk.media:ijkplayer-armv7a:0.8.8'
}
```
阅读全文