Andreas's answer is the right way to do this, but this code does not get the absolute path to the file. This forces mMediaPlayer.prepare(); throw an IOException: Prepare failed. status=0x1 IOException: Prepare failed. status=0x1 .
Here is the code to get the file path along with the file name:
private String[] mAudioPath; private MediaPlayer mMediaPlayer; private String[] mMusicList; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mMediaPlayer = new MediaPlayer(); ListView mListView = (ListView) findViewById(R.id.listView1); mMusicList = getAudioList(); ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mMusicList); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { try { playSong(mAudioPath[arg2]); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); } private String[] getAudioList() { final Cursor mCursor = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA }, null, null, "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC"); int count = mCursor.getCount(); String[] songs = new String[count]; String[] mAudioPath = new String[count]; int i = 0; if (mCursor.moveToFirst()) { do { songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)); mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)); i++; } while (mCursor.moveToNext()); } mCursor.close(); return songs; }
Now that we have the absolute path, we do not need to get the path again. So:
private void playSong(String path) throws IllegalArgumentException, IllegalStateException, IOException { Log.d("ringtone", "playSong :: " + path); mMediaPlayer.reset(); mMediaPlayer.setDataSource(path);
Be sure to use:
playSong(mAudioPath[arg2]);
instead:
playSong(mMusicList[arg2]);
in the ListView OnItemClickListener list.
To get only the name of the track (looks more elegant than the whole filename with the extension), use:
`MediaStore.Audio.Media.TITLE`
instead:
`MediaStore.Audio.Media.DISPLAY_NAME`
Vikram Gupta
source share