2017-09-26 47 views
0

我正在使用Exo Player为了制作android的音频播放器。到目前为止,我正在使用此代码并从手机中获取以下信息。数据,名称,艺术家。获取歌曲的确切路径并构建URI

public void getMp3Songs() { 
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
    String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0"; 
    Cursor cursor = getContentResolver().query(uri, null, selection, null, null); 
    if (cursor != null) { 
     if (cursor.moveToFirst()) { 
      do { 
       String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); 
       String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)); 
       String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); 
       int songId = cursor.getColumnIndex(MediaStore.Audio.Media._ID); 
       arrayList.add(new Songs(songId, name, url)); 


      } while (cursor.moveToNext()); 

     } 

     cursor.close(); 
    } 
} 

接下来我需要的是这些轨道的确切路径。 为此我使用此代码。

private void initializePlayer(){ 
    player = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(this), new DefaultTrackSelector() 
       , new DefaultLoadControl()); 

    simpleExoPlayerView.setPlayer(player); 
    player.setPlayWhenReady(playWhenReady); 
    player.seekTo(currentWindow,playbackPosition); 

    Uri uri = Uri.parse(url); 
    MediaSource mediaSource = buildMediaSource(uri); 
    player.prepare(mediaSource, true, false); 
} 

private MediaSource buildMediaSource(Uri uri) { 
    return new ExtractorMediaSource(uri, 
      new DefaultHttpDataSourceFactory("ua"), 
      new DefaultExtractorsFactory(), null, null); 
} 

问题是,当我启动播放器时,没有任何反应。它只是一个空白的球员,它不玩任何东西。我想我在这里弄乱了文件路径。请帮忙。

+1

“我需要的下一件事就是这些曲目的确切路径” - 你不应该,特别是因为你无法获得一切。使用'_ID'为'ContentUris.withAppendedId()'生成一个'Uri',并在ExoPlayer中使用'Uri'。 – CommonsWare

+0

我不能。我只是不知道该怎么做。我到处搜索。你能提供一些示例代码吗? –

+0

'ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,songId)' – CommonsWare

回答

0

好吧,所以我找到了解决方案,如果有人需要他可以使用它。问题不在于获取地址或建立Uri。这是在这个特定的部分。 new DefaultHttpDataSourceFactory("ua")更改为这样:

DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this, 
      Util.getUserAgent(this, "idk"), new DefaultBandwidthMeter()); 

在返回MediaSource现在用这个实例。