2013-03-04 83 views
1

如何使用managedQuery()從android中的特定文件夾獲取所有音頻文件。意思是應該在managedQuery()中的where子句中過濾Cursor結果。獲取文件夾中的所有音頻文件

代碼是:

String[] proj = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DURATION }; 
Cursor cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,proj, /*where clause here*/, null, null); 

回答

1

我想你檢查文件的擴展名來檢查它是否在上面的代碼

public class ReadAllFilesFromPathActivity extends Activity { 
private List<String> myList; 
File file; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
ListView listView = (ListView) findViewById(R.id.mylist); 
myList = new ArrayList<String>(); 

File directory = Environment.getExternalStorageDirectory(); 
file = new File(directory + "/Test"); 
File list[] = file.listFiles(); 

for(int i=0; i< list.length; i++) 
{ 
    if(checkFileExtension(list[i].getName()) 
    { 
     myList.add(list[i].getName()); 
    } 
} 
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
     android.R.layout.simple_list_item_1, android.R.id.text1, myList); 
listView.setAdapter(adapter); //Set all the file in the list. 
} 
} 

媒體文件或不添加以下方法檢查擴展。擴展枚舉添加支持的擴展

private boolean checkExtension(String fileName) { 
    String ext = getFileExtension(fileName); 
    if (ext == null) return false; 
    try { 
     if (SupportedFileFormat.valueOf(ext.toUpperCase()) != null) { 
      return true; 
     } 
    } catch(IllegalArgumentException e) { 
     return false;  
    } 
    return false; 
} 

public String getFileExtension(String fileName) { 
    int i = fileName.lastIndexOf('.'); 
    if (i > 0) { 
     return fileName.substring(i+1); 
    } else 
     return null; 
} 

和枚舉(你也可以添加你自己的)

public enum SupportedFileFormat 
{ 
    _3GP("3gp"), 
    MP4("mp4"), 
    M4A("m4a"), 
    AAC("aac"), 
    TS("ts"), 
    FLAC("flac"), 
    MP3("mp3"), 
    MID("mid"), 
    XMF("xmf"), 
    MXMF("mxmf"), 
    RTTTL("rtttl"), 
    RTX("rtx"), 
    OTA("ota"), 
    IMY("imy"), 
    OGG("ogg"), 
    MKV("mkv"), 
    WAV("wav"); 

    private String filesuffix; 

    SupportedFileFormat(String filesuffix) { 
     this.filesuffix = filesuffix; 
    } 

    public String getFilesuffix() { 
     return filesuffix; 
    } 
} 

這是一個有點更多的代碼,但是可以幫助你

+0

thnks它對我的工作,,,投票了.. – 2015-06-04 12:21:06

4

IS_MUSIC!= 0 AND DATA LIKE'/ dir /%':

String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0 AND " + 
      MediaStore.Audio.Media.DATA + " LIKE '/mnt/sdcard/Music/SomeArtist/%'"; 

這會將您的managedQuery結果限制爲.../SomeArtist/dir。

相關問題