我已经制作了一个应用程序,我想从SD卡中选择一首歌,所选歌曲的路径应该返回到onActivityResult(),这样我就可以做bla bla bla ..我怎么能得到它?任何帮助非常感谢。这对我来说非常重要。
代码:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add("Pick Song");
return super.onCreateOptionsMenu(menu);
}
protected File getTempFile()
{
dir =new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Music");
return dir;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
//System.gc();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/mp3");
Uri data = Uri.fromFile(getTempFile());
intent.setData(data);
startActivityForResult(intent, Pick_song);
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case Pick_song : if ((resultCode == RESULT_OK)&&(data != null))
{
final String ringTonePath = data.getData().getEncodedPath();
Button playbutton = (Button)findViewById(R.id.play);
playbutton.setVisibility(0);
playbutton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
try
{
mMediaPlayer.setDataSource(ringTonePath);
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
mp.release();
mp = null;
}
});
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
});
}
}
}
更新:我在setDataSource()中得到NUll指针Excepton。因为我得到的歌曲的内容不是URI.thats我有NPE。如何解决?
答案 0 :(得分:1)
我得到了答案
代码:
System.gc();
mMediaPlayer = new MediaPlayer();
if(mMediaPlayer.isPlaying())
{
mMediaPlayer.reset();
}
String[] proj = { MediaStore.Images.Media.DATA };
musiccursor = managedQuery(mUri, proj, null, null, null);
music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
musiccursor.moveToFirst();
String filename = musiccursor.getString(music_column_index);
mMediaPlayer.setDataSource(filename);
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
mp.release();
mp = null;
}
});
通过这个我们可以轻松地将内容uri转换为文件uri。
答案 1 :(得分:0)
根据Using Intent.ACTION_PICK for specific path,您似乎无法使用ACTION_PICK
指定目录。但是,如果你绕过ACTION_PIC& amp;只需实现一个浏览对话框。有关实现浏览对话框的帮助,请查看Choose File Dialog。
HTH,
阿克沙伊