安卓系統在開機的時候就會自動檢測SD卡的檔案,並將音樂檔案搜集產生一個資料庫檔案。我們只需訪問資料庫表中的資訊就能得到所需的檔案代碼如下
<span style="font-size:14px; white-space: pre;"> </span><span style="font-size:14px;">// 擷取所有歌曲 Cursor cursor = cr.query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);</span>
得到cursor對象就能訪問cursor裡的媒體資源
if (cursor.moveToFirst()) { do { String title = cursor.getString(cursor .getColumnIndex(MediaStore.Audio.Media.TITLE)); String singer = cursor.getString(cursor .getColumnIndex(MediaStore.Audio.Media.ARTIST)); String album = cursor.getString(cursor .getColumnIndex(MediaStore.Audio.Media.ALBUM)); long size = cursor.getLong(cursor .getColumnIndex(MediaStore.Audio.Media.SIZE)); long time = cursor.getLong(cursor .getColumnIndex(MediaStore.Audio.Media.DURATION)); String url = cursor.getString(cursor .getColumnIndex(MediaStore.Audio.Media.DATA)); int _id = cursor.getInt(cursor .getColumnIndex(MediaStore.Audio.Media._ID)); String name = cursor.getString(cursor .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); String sbr = name.substring(name.length() - 3, name.length()); } while (cursor.moveToNext()); <p> </p> <p> <span style="font-size:14px; color:#3366ff; background-color:rgb(255,255,255)">但是如果你的手機在開機後又下載了新的歌曲檔案通過上面的方法是訪問不到的,因為它還沒有被加到資料表中,這樣我們就要重寫檔案搜尋的方法。</span> </p> <p> <br> </p> <pre name="code" class="java">//擷取該路徑下的所有檔案 public static List<String> getAllFile(String path){ List<String> fileList = new ArrayList<String>(); File folder = new File(path); addFile(fileList, folder); return fileList; } public static void addFile(List<String> fileList,File f){ if(f.isDirectory()){ File[] files = f.listFiles(); for(File f1 : files){ addFile(fileList, f1); } }else{ String filename = f.getName(); if(filename.length()>4&&filename.substring(filename.length()-4).equalsIgnoreCase(".mp3")){ fileList.add(f.getAbsolutePath()); } } }</pre><span style="font-size:14px"><br> </span>我們只需在需要的地方調用<pre name="code" class="java">getAllFile(Environment.getExternalStorageDirectory().getAbsolutePath());</pre><br> <br> <pre></pre> <p></p> <pre></pre>