2017-06-13 46 views
0

我試圖從內部手機存儲獲取所有mp3文件。我沒有外部SD卡。我無法訪問MP3任何時間結果爲零?訪問手機內存中的所有mp3文件 - Android

下面是代碼:

public ArrayList<File> findSongs(File root) { 
    ArrayList<File> al = new ArrayList<File>(); 
    File[] files = root.listFiles(); 
    for(File singleFile : files) { 
     if (singleFile.isDirectory() && !singleFile.isHidden()) { 
      al.addAll(findSongs(singleFile)); 
     } else if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")) { 
      al.add(singleFile); 
      System.out.println(singleFile.getName()); 
     } 
    } 
    return al; 
} 

並調用該方法如下圖所示:

songs = findSongs(Environment.getExternalStorageDirectory()); 
+1

哪裏是問題嗎? –

+0

我沒有得到MP3的所有時間結果將爲零。 – user2856484

+1

查詢音頻/ mp3文件的'MediaStore'。這將會**更快,更可靠。 – CommonsWare

回答

0

你可以嘗試這樣的事:

public void getSongsList() { 
    List<String> fullsongpath = new ArrayList<>(); 
    Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"; 

    Cursor cursor = managedQuery(allsongsuri, null, selection, null, null); 

    if (cursor != null) { 
     if (cursor.moveToFirst()) { 
      do { 
       String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); 
       int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)); 

       String songPath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); 
       fullsongpath.add(songPath); 
       String artistName = cursor.getString(cursor 
         .getColumnIndex(MediaStore.Audio.Media.ARTIST)); 
       int artistId = cursor.getInt(cursor 
         .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)); 
       String albumName = cursor.getString(cursor 
         .getColumnIndex(MediaStore.Audio.Media.ALBUM)); 
       int albumId = cursor.getInt(cursor 
         .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)); 

      } while (cursor.moveToNext()); 
     } 
     cursor.close(); 
    } 
} 
相關問題