我正在开发一个应用程序,用户将选择一个音频文件并播放音频。 然后我会将音频传递给下一个活动。
以下是我选择音频的代码,但它会给出错误setDataSource Failed:Status=0X80000000
,请指导我该怎么做
switch(v.getId())
{
case R.id.btnmusic:
/*Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File file = new File("file:///sdcard/Music");
intent.setDataAndType(Uri.fromFile(file), "audio/*");*/
Intent pickMedia = new Intent(Intent.ACTION_GET_CONTENT);
pickMedia.setType("audio/*");
startActivityForResult(pickMedia,1);
break;
protected void onActivityResult(int RequestCode,int ResultCode,Intent data)
{
if(RequestCode==1)
{
if(data != null)
{
Uri muri=data.getData();
String uri=muri.getPath();
File track=new File(uri);
if(uri != null)
{
Uri urinew = MediaStore.Audio.Media.getContentUriForPath(track.getAbsolutePath());
//Toast.makeText(this, uri, Toast.LENGTH_SHORT).show();
MediaPlayer md=new MediaPlayer();
try{
md.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
md.setDataSource(AudioSelect.this, urinew);
md.prepare();
md.start();
}
catch(Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
}
else
{
Toast.makeText(this, "No Image Data Recieved", Toast.LENGTH_SHORT).show();
}
}
}
}
答案 0 :(得分:1)
1:使用Intent从SD卡中选择音频文件:
Intent audioIntent = new Intent();
audioIntent.setType("audio/*");
audioIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(audioIntent,PICK_AUDIO_REQUEST);
2:处理OnActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || data == null || data.getData() == null) {
// error
return;
}
if (requestCode == PICK_AUDIO_REQUEST) {
try {
Uri uri= data.getData();
String path = getRealPathFromURI(uri);
// play audio file using MediaPlayer
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:getRealPathFromURI
是一种实用方法:
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
答案 1 :(得分:0)
md = MediaPlayer.create(this, Uri.parse(track.getAbsolutePath()));