Search code examples
androidmedia-player

Android not playing song when a URI is set as datasource


I am developing a music application and want to play a song when a URI is set as datasource, but setDataSource is not accepting the String. I mean how can we write the URI for a particular ID.

Here is the code:

MediaPlayer mp = new MediaPlayer();
mp.reset();
String sel = MediaStore.Audio.Media._ID+"=166";
mp.setDataSource(context,sel);
mp.prepare();
mp.start();

Here 166 is the ID of a particular song in my phone.


Solution

  • Try setting your URI properly

    Use

    Uri fileUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 166);
    mp.setDataSource(context, fileUri);
    

    Use MediaStore.Audio.Media.INTERNAL_CONTENT_URI if your audio is using being stored on your device's internal storage