Android獲取Camera錄制的視頻的地理位置

前段時間在做視頻播放器的時候碰到一個新需求:需要將視頻的地理位置顯示在視頻的詳情里面。第一反應(yīng)就是每一個視頻文件都可以記錄下來一些信息范咨,這些信息里面包含了經(jīng)緯度等等熊楼,就像照片的ExifInterface類一樣峦睡。于是就去查看了MediaRecorder類辣往,便發(fā)現(xiàn)了這個類里面有public void setLocation(float latitude, float longitude)這么個方法可以給錄制的視頻設(shè)置經(jīng)緯度。

/**
     * Set and store the geodata (latitude and longitude) in the output file.
     * This method should be called before prepare(). The geodata is
     * stored in udta box if the output format is OutputFormat.THREE_GPP
     * or OutputFormat.MPEG_4, and is ignored for other output formats.
     * The geodata is stored according to ISO-6709 standard.
     *
     * @param latitude latitude in degrees. Its value must be in the
     * range [-90, 90].
     * @param longitude longitude in degrees. Its value must be in the
     * range [-180, 180].
     *
     * @throws IllegalArgumentException if the given latitude or
     * longitude is out of range.
     *
     */
    public void setLocation(float latitude, float longitude) {
        int latitudex10000  = (int) (latitude * 10000 + 0.5);
        int longitudex10000 = (int) (longitude * 10000 + 0.5);

        if (latitudex10000 > 900000 || latitudex10000 < -900000) {
            String msg = "Latitude: " + latitude + " out of range.";
            throw new IllegalArgumentException(msg);
        }
        if (longitudex10000 > 1800000 || longitudex10000 < -1800000) {
            String msg = "Longitude: " + longitude + " out of range";
            throw new IllegalArgumentException(msg);
        }

        setParameter("param-geotag-latitude=" + latitudex10000);
        setParameter("param-geotag-longitude=" + longitudex10000);
    }

所以說明視頻文件里面是存儲了經(jīng)緯度的姿鸿,現(xiàn)在的關(guān)鍵就是找到對應(yīng)的API去獲取視頻文件存儲的經(jīng)緯度谆吴。回憶以前獲取視頻的某一幀圖像使用的是MediaMetadataRetriever類苛预,通過這個對象是否也可以獲取一些別的信息呢句狼?創(chuàng)建mediaMetadataRetriever對象后發(fā)現(xiàn)了這么個方法:mediaMetadataRetriever.extractMetadata(int keyCode);看見這個方法名就感覺找到了(提煉出元數(shù)據(jù)),現(xiàn)在還需要一個關(guān)鍵的keyCode热某。于是進入到這個類里面瀏覽源碼腻菇,發(fā)現(xiàn)了一大堆的key:

/**
     * The metadata key to retrieve the numeric string describing the
     * order of the audio data source on its original recording.
     */
    public static final int METADATA_KEY_CD_TRACK_NUMBER = 0;
    /**
     * The metadata key to retrieve the information about the album title
     * of the data source.
     */
    public static final int METADATA_KEY_ALBUM           = 1;
    /**
     * The metadata key to retrieve the information about the artist of
     * the data source.
     */
    public static final int METADATA_KEY_ARTIST          = 2;
    /**
     * The metadata key to retrieve the information about the author of
     * the data source.
     */
    public static final int METADATA_KEY_AUTHOR          = 3;
    /**
     * The metadata key to retrieve the information about the composer of
     * the data source.
     */
    public static final int METADATA_KEY_COMPOSER        = 4;
    /**
     * The metadata key to retrieve the date when the data source was created
     * or modified.
     */
    public static final int METADATA_KEY_DATE            = 5;
    /**
     * The metadata key to retrieve the content type or genre of the data
     * source.
     */
    public static final int METADATA_KEY_GENRE           = 6;
    /**
     * The metadata key to retrieve the data source title.
     */
    public static final int METADATA_KEY_TITLE           = 7;
    /**
     * The metadata key to retrieve the year when the data source was created
     * or modified.
     */
    public static final int METADATA_KEY_YEAR            = 8;
    /**
     * The metadata key to retrieve the playback duration of the data source.
     */
    public static final int METADATA_KEY_DURATION        = 9;
    /**
     * The metadata key to retrieve the number of tracks, such as audio, video,
     * text, in the data source, such as a mp4 or 3gpp file.
     */
    public static final int METADATA_KEY_NUM_TRACKS      = 10;
    /**
     * The metadata key to retrieve the information of the writer (such as
     * lyricist) of the data source.
     */
    public static final int METADATA_KEY_WRITER          = 11;
    /**
     * The metadata key to retrieve the mime type of the data source. Some
     * example mime types include: "video/mp4", "audio/mp4", "audio/amr-wb",
     * etc.
     */
    public static final int METADATA_KEY_MIMETYPE        = 12;
    /**
     * The metadata key to retrieve the information about the performers or
     * artist associated with the data source.
     */
    public static final int METADATA_KEY_ALBUMARTIST     = 13;
    /**
     * The metadata key to retrieve the numberic string that describes which
     * part of a set the audio data source comes from.
     */
    public static final int METADATA_KEY_DISC_NUMBER     = 14;
    /**
     * The metadata key to retrieve the music album compilation status.
     */
    public static final int METADATA_KEY_COMPILATION     = 15;
    /**
     * If this key exists the media contains audio content.
     */
    public static final int METADATA_KEY_HAS_AUDIO       = 16;
    /**
     * If this key exists the media contains video content.
     */
    public static final int METADATA_KEY_HAS_VIDEO       = 17;
    /**
     * If the media contains video, this key retrieves its width.
     */
    public static final int METADATA_KEY_VIDEO_WIDTH     = 18;
    /**
     * If the media contains video, this key retrieves its height.
     */
    public static final int METADATA_KEY_VIDEO_HEIGHT    = 19;
    /**
     * This key retrieves the average bitrate (in bits/sec), if available.
     */
    public static final int METADATA_KEY_BITRATE         = 20;
    /**
     * This key retrieves the language code of text tracks, if available.
     * If multiple text tracks present, the return value will look like:
     * "eng:chi"
     * @hide
     */
    public static final int METADATA_KEY_TIMED_TEXT_LANGUAGES      = 21;
    /**
     * If this key exists the media is drm-protected.
     * @hide
     */
    public static final int METADATA_KEY_IS_DRM          = 22;
    /**
     * This key retrieves the location information, if available.
     * The location should be specified according to ISO-6709 standard, under
     * a mp4/3gp box "@xyz". Location with longitude of -90 degrees and latitude
     * of 180 degrees will be retrieved as "-90.0000+180.0000", for instance.
     */
    public static final int METADATA_KEY_LOCATION        = 23;
    /**
     * This key retrieves the video rotation angle in degrees, if available.
     * The video rotation angle may be 0, 90, 180, or 270 degrees.
     */
    public static final int METADATA_KEY_VIDEO_ROTATION = 24;
    /**
     * This key retrieves the original capture framerate, if it's
     * available. The capture framerate will be a floating point
     * number.
     */
    public static final int METADATA_KEY_CAPTURE_FRAMERATE = 25;

這里我所需要的僅僅是:public static final int METADATA_KEY_LOCATION = 23;

/**
     * 獲取視頻保存的地理位置信息
     *
     * @return +22.000+119.999
     */
    public static String getVideoLocationInfo(String path) {
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
        try {
            metadataRetriever.setDataSource(path);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION);
    }

返回的經(jīng)緯度格式:+22.000+119.999,這里需要將經(jīng)度部分和緯度部分分割開來昔馋。

String s = getVideoLocationInfo(videoPath);
        if(!TextUtils.isEmpty(s)){
                char[]chars=s.toCharArray();
                String latitude=null;
                String longitude=null;
                for(int i=0;i<chars.length;i++){
        if((chars[i]=='+'||chars[i]=='-')&&i>0){
        latitude=s.substring(0,i);
        longitude=s.substring(i,chars.length);
        break;
        }
        }
        double dLat=Double.parseDouble(latitude);
        double dLon=Double.parseDouble(longitude);
        }

最后通過Geocoder解析出經(jīng)緯度對應(yīng)的具體城市位置:

@WorkerThread
    private static void getAddress(Activity a, double latitude, double longitude, final TextView localeTxt) {
        Geocoder geocoder = new Geocoder(a);
        final StringBuilder stringBuilder = new StringBuilder();
        try {
            //根據(jù)經(jīng)緯度獲取地理位置信息
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                String countryName = address.getCountryName();//國家
                String adminArea = address.getAdminArea();//省份
                String locality = address.getLocality();//市
                String subLocality = address.getSubLocality();//區(qū)
                String thoroughfare = address.getThoroughfare();//街道
                if (!TextUtils.isEmpty(countryName)) {
                    stringBuilder.append(countryName).append(a.getResources().getString(R.string.divide));
                }
                if (!TextUtils.isEmpty(adminArea)) {
                    stringBuilder.append(adminArea).append(a.getResources().getString(R.string.divide));
                }
                if (!TextUtils.isEmpty(locality)) {
                    stringBuilder.append(locality).append(a.getResources().getString(R.string.divide));
                }
                if (!TextUtils.isEmpty(subLocality)) {
                    stringBuilder.append(subLocality).append(a.getResources().getString(R.string.divide));
                }
                if (!TextUtils.isEmpty(thoroughfare)) {
                    stringBuilder.append(thoroughfare).append(a.getResources().getString(R.string.divide));
                }
                stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(a.getResources().getString(R.string.divide)));
            }
        } catch (IOException e) {
            e.printStackTrace();
            a.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    localeTxt.setVisibility(View.GONE);
                }
            });
        }
        final String s = stringBuilder.toString();
        if (!TextUtils.isEmpty(s)) {
            a.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    localeTxt.setText(s);
                }
            });
        } else {
            a.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    localeTxt.setVisibility(View.GONE);
                }
            });
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末筹吐,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子秘遏,更是在濱河造成了極大的恐慌丘薛,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件垄提,死亡現(xiàn)場離奇詭異榔袋,居然都是意外死亡周拐,警方通過查閱死者的電腦和手機铡俐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來妥粟,“玉大人审丘,你說我怎么就攤上這事」锤” “怎么了滩报?”我有些...
    開封第一講書人閱讀 152,543評論 0 341
  • 文/不壞的土叔 我叫張陵锅知,是天一觀的道長。 經(jīng)常有香客問我脓钾,道長售睹,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,221評論 1 279
  • 正文 為了忘掉前任可训,我火速辦了婚禮昌妹,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘握截。我一直安慰自己飞崖,他們只是感情好,可當我...
    茶點故事閱讀 64,224評論 5 371
  • 文/花漫 我一把揭開白布谨胞。 她就那樣靜靜地躺著固歪,像睡著了一般。 火紅的嫁衣襯著肌膚如雪胯努。 梳的紋絲不亂的頭發(fā)上牢裳,一...
    開封第一講書人閱讀 49,007評論 1 284
  • 那天,我揣著相機與錄音康聂,去河邊找鬼贰健。 笑死,一個胖子當著我的面吹牛恬汁,可吹牛的內(nèi)容都是我干的伶椿。 我是一名探鬼主播,決...
    沈念sama閱讀 38,313評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼氓侧,長吁一口氣:“原來是場噩夢啊……” “哼脊另!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起约巷,我...
    開封第一講書人閱讀 36,956評論 0 259
  • 序言:老撾萬榮一對情侶失蹤偎痛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后独郎,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體踩麦,經(jīng)...
    沈念sama閱讀 43,441評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,925評論 2 323
  • 正文 我和宋清朗相戀三年氓癌,在試婚紗的時候發(fā)現(xiàn)自己被綠了谓谦。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,018評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡贪婉,死狀恐怖反粥,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤才顿,帶...
    沈念sama閱讀 33,685評論 4 322
  • 正文 年R本政府宣布莫湘,位于F島的核電站,受9級特大地震影響郑气,放射性物質(zhì)發(fā)生泄漏幅垮。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,234評論 3 307
  • 文/蒙蒙 一尾组、第九天 我趴在偏房一處隱蔽的房頂上張望军洼。 院中可真熱鬧,春花似錦演怎、人聲如沸匕争。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽甘桑。三九已至,卻和暖如春歹叮,著一層夾襖步出監(jiān)牢的瞬間跑杭,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評論 1 261
  • 我被黑心中介騙來泰國打工咆耿, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留德谅,地道東北人。 一個月前我還...
    沈念sama閱讀 45,467評論 2 352
  • 正文 我出身青樓萨螺,卻偏偏與公主長得像窄做,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子慰技,可洞房花燭夜當晚...
    茶點故事閱讀 42,762評論 2 345

推薦閱讀更多精彩內(nèi)容