Raw方式
MediaPlayer mediaPlayer = null;
mediaPlayer = MediaPlayer.create(MainActivity2.this, R.raw.media2);
mediaPlayer.start();
assets
// open file
AssetManager assetManager = getAssets();
try {
AssetFileDescriptor assetFileDescriptor = assetManager.openFd("media1.mp3");
// load music
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
SDcard
-
首先需要添加
implementation 'com.lovedise:permissiongen:0.0.6'
-
静态请求权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
-
动态请求
PermissionGen.with(MainActivity2.this) .addRequestCode(SDCARD_CODE) .permissions( Manifest.permission.READ_EXTERNAL_STORAGE, ) .request(); @PermissionSuccess(requestCode = SDCARD_CODE) public void requestSdCardSuccess(){ //成功之后的处理 playMnt(); } @PermissionFail(requestCode = SDCARD_CODE) public void requestSdCardFail() { Toast.makeText(MainActivity2.this, "失败", Toast.LENGTH_LONG).show(); }
-
playMnt的播放方法
private void playMnt() { mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource("/mnt/sdcard/Music/media3.mp3"); mediaPlayer.prepare(); mediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } }
-
如何在模拟器中添加音乐
- 详细代码参见 点击跳转