Android应用程序Mp3文件mimetype解析为空



我正在尝试获取存储在下载中的mp3的mime类型。问题是mimetype总是返回null。我不知道为什么。注意,将扩展名改为小写(.mp3)没有什么区别。

String filePath = "/storage/emulated/0/Download/song.MP3";
File file = new File(filePath);
Uri uri2 = Uri.fromFile(file);
//will display /storage/emulated/0/Download/song.MP3
Log.d("file type as string",file.toString());
//will display file:///storage/emulated/0/Download/song.MP3
Log.d("uri type as string",uri2.toString());

ContentResolver cR = getApplicationContext().getContentResolver();
String mime = cR.getType(uri2);
//mime is null always displays
if(mime == null){
    Log.d("result", "mime is null");
} else{
    Log.d("mime", mime);
}
String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(filePath);
String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

System.out.println("extension:" +extension); //displays MP3
System.out.println("mimetype:" + mimetype); //displays null

检查下面这段代码。你会明白为什么你没有得到所需的输出。

    String type = null;
    String extension = "mp3";
    type = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    Log.d(TAG,"mime type1 "+type);
    extension = "MP3";
    type = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    Log.d(TAG,"mime type2 "+type);

如果您无法在将文件扩展名改为小写的基础上做出任何改变,请考虑使用

File filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File mov = new File(filesDir,"song.mp3");

并使用文件的绝对路径而不是硬编码路径来构造uri。

最新更新