我想用MediaPlayer播放音频文件。音频文件不在资源中。 我想做的就是这样。
当我调用MediaPlayer #setDataSource(path)时发生IOException。 我不知道我在哪里做错了
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_choose) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 999);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 999 && resultCode == RESULT_OK) {
final Uri uri = data.getData();
_realmObj.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm bgRealm) {
MyDb db = bgRealm.where(Song.class).equalTo("id", songIndex).findFirst();
db.setSongPath(uri.getDataString());
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
buttonPlay.setVisibility(View.VISIBLE);
}
});
}
super.onActivityResult(requestCode, resultCode, data);
}
private void PlaySong(int songIndex) {
MyDb db = _realmObj.where(Song.class).equalTo("id", songIndex).findFirst();
Uri path = db.getSongPath();
if (path == null) {
return;
}
try {
_mediaPlayer.setDataSource(URLDecoder.decode(path, "utf-8"));
_mediaPlayer.prepare();
_mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}