2017-04-01 91 views
0

我创建的音频播放器,我使用此代码来获取所有的歌曲如何避免不支持的格式的音频播放器

String[] STAR = {"*"}; 

    Cursor cursor; 
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"; 

     File file; 

    cursor =context.getContentResolver().query(uri, STAR, selection, null, null); 

    if (cursor != null) { 

     if (cursor.moveToFirst()) { 
      int i = 0; 
      do { 



       String songName = cursor 
         .getString(cursor 
           .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); 

       path[i] = cursor.getString(cursor 
         .getColumnIndex(MediaStore.Audio.Media.DATA)); 


       String albumName = cursor.getString(cursor 
         .getColumnIndex(MediaStore.Audio.Media.ALBUM)); 
       albumId[i] = cursor 
         .getInt(cursor 
           .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)); 

       String artist= cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)); 
       String albumname= cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)); 
       artistId[i]=cursor.getInt(cursor 
           .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)); 



     }cursor.close(); 

这让我的歌,但我得到的不支持的格式的音频太多。如.wav任何想法如何避免不受支持的格式

+0

你需要添加的MimeType检查。请查看如何添加支票的示例。 – Geek

回答

0

您可以使用MimeType来做到这一点。请参阅下面的示例代码,了解它是如何完成的。

ContentResolver contentResolver = context.getContentResolver(); 
Uri uri = MediaStore.Files.getContentUri("external"); 
String[] projection = null; 
String sortOrder = null; 
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?"; 
String mimeType = imeTypeMap.getSingleton().getMimeTypeFromExtension("mp3"); 
String[] selectionArgsMp3 = new String[]{ mimeType }; 
Cursor mp3Songs = contentResolver.query(uri, projection,selectionMimeType,selectionArgsmp3, sortOrder); 

另一种方法是,你可以检查是否有使用下面的代码而打开/播放应用安装在设备的任何兼容的应用程序。

private void openRelevantFileHandler(String pathToMusicFile) 
{ 
    String extension = MimeTypeMap.getFileExtensionFromUrl(pathToMusicFile); 
    String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); 

    Intent intent = new Intent(); 
    intent.setAction(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.parse("file://" + pathToMusicFile), type); 

    PackageManager packageManager = context.getPackageManager(); 
    List activities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL); 
    boolean isIntentSafe = activities.size() > 0; 
    if (!isIntentSafe) { 
     Utility.showToast(context, "No application available on your device to open this type of file."); 
    } 
    else 
    { 
     context.startActivity(intent);//Start related application 
    } 
} 

希望这将帮助你以某种方式:)

相关问题