我正在尝试从文件路径创建媒体播放器
private void play(String path) {
MediaPlayer player = null;
if (path.startsWith("assets/music")) {
path = path.replace("assets/", "");
AssetFileDescriptor afd;
try {
afd = mActivity.getAssets().openFd(path);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
player.prepare();
} catch (IOException e) {
Log.e(TAG, e.toString());
}
} else {
player = MediaPlayer.create(mActivity, Uri.parse(path));
}
if (player != null) {
player.setOnCompletionListener(releaseListener);
player.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(TAG, "mp error: " + what + ", extra: " + extra);
return true;
}
});
player.start();
mPlayer = player;
}
}
从资产路径它的工作原理但是MediaPlayer.create(mActivity,Uri.parse(path));总是返回null
完整路径
/ storage / emulated / 0 /下载/ Buzzer - 1.mp3
资产路径
assets / music / Buzzer - 1.mp3
答案 0 :(得分:0)
如果您说传递给path
的{{1}}的值为Uri.parse(path)
,则该值不是有效/storage/emulated/0/Download/Buzzer - 1.mp3
。值得注意的是,没有计划。之一:
传递指向所需文件的Uri
并使用File
或
确保Uri.fromFile()
有一个方案(例如path
)