根據音頻文件的路徑獲取其Uri

本博客參考以下博客寫的:文件路徑和Uri -- kwongfung的專欄

下面是包裝好的方法,輸入參數爲錄音文件的path,返回值爲它在媒體庫中對應的Uri;

例如以下調用:

String path = "/storage/emulated/0/Recoeder/REC201612075435.mp3";

Uri uri = queryUriForAudio(path);

logd("uritest","Uri : "+uri.toString());

利用log打印出來就是這樣的:

12-07 15:27:33.619 16562-24774/com.bbk.recorder D/uritest: Uri :content://media/external/audio/media/10901


有時候如果某個音頻文件如錄音文件剛剛生成,媒體庫還沒來得及更新的話,這時候獲取到的Uri會爲空null,如果是獲取早就存在的音頻文件的Uri就不會有這個問題!


/**
 * 查找在於SDcard中的Audio文件對應於MediaStore  uri
 * @param path 音頻文件
 * @return Uri
 */
public Uri queryUriforAudio(String path)
{
    File file = new File(path);
    final String where = MediaStore.Audio.Media.DATA + "='"+file.getAbsolutePath()+"'";
    Cursor cursor = this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, where, null, null);
    if (cursor == null) {
        Log.d("uritest", "queryUriforAudio: uri爲空 1");
        return null;
    }
    int id = -1;
    if (cursor != null) {
        cursor.moveToFirst();
        if (!cursor.isAfterLast()) {
            id = cursor.getInt(0);
        }
        cursor.close();
    }
    if(id==-1)
    {
        Log.d("uritest", "queryUriforAudio: uri爲空 2");
        return null;
    }
    return Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
}


發佈了36 篇原創文章 · 獲贊 45 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章