以编程方式检查下载的 MP3/OGG 文件是否在 android 中 valid/complete

Check programmatically if a downloaded MP3/OGG file is valid/complete in android

我正在从用户提供的 URLs 以编程方式下载音频文件 MP3/OGG​​。我进一步将下载的文件设置为 ringtone/alarmtone。但是,我需要以编程方式验证下载的文件是有效的 MP3/OGG 文件并且可以播放。有什么方法可以确保下载的文件是有效的 MP3/OGG 文件,而不是来自假 URL 的垃圾 header。

我用来下载的代码:

try {
        URL url = new URL(link);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("GET");
        httpConn.setReadTimeout(20000);
        httpConn.setConnectTimeout(10000);
        httpConn.connect();
        int responseCode = httpConn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            Log.i(TAG, "http response error code "+responseCode+" for "+name);
            return -1;
        }

        int lenghtOfFile = httpConn.getContentLength();
        Log.d(TAG, "Length of file to download: " + lenghtOfFile + " for " + name + " id_download "+id_download);
        if (lenghtOfFile == -1) {
            return -1; // no length to download
        }
        // input stream to read file - with 8k buffer
        input = new BufferedInputStream(httpConn.getInputStream(),1000000);

        // Delete the outfile first
        File deleteFile = new File(outfile);
        if (deleteFile.exists()) {
            if (deleteFile.delete())
                Log.i(TAG, "File deleted " + outfile);
            else
                Log.i(TAG, "File could'nt be deleted " + outfile);
        }

        output = new FileOutputStream(outfile);
        byte data[] = new byte[1000000];

        long total = 0;
        int progress = 0;
        long mLastUpdate = 0;

        int count = 0;
        while ((count = input.read(data)) != -1) {
            total += count;
            progress = (int) ((total * 100) / lenghtOfFile);
            Log.d(TAG, name + " progress " + progress+"  count "+count+" total "+total);
            output.write(data, 0, count);
            if (System.currentTimeMillis() - mLastUpdate > 1000) {
                mLastUpdate = System.currentTimeMillis();
            }
        }

        output.flush();
    } catch (Exception e) {
        Log.e(TAG, "Exception in downloadUrl() " + e + " for " + name + "  " + id_download + "  "+task_id);
        return -1;
    } finally {
        try {
            if (output != null) {
                output.close();
            }
            if (input != null) {
                input.close();
            }
            if (httpConn != null) {
                httpConn.disconnect();
            }
        } catch (Exception ex) {
            Log.e(TAG,"Exception in close "+ex);
        }
    }

您可以检查下载流的结尾,如果它被调用,则表明您下载的文件具有完整的长度。 如果对您有用,请接受这个答案吗? 谢谢

我使用 MediaMetadataRetriever 类的 API "extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)" 解决了这个问题。如果它是一个有效的 mp3/ogg 文件,那么这个 return 是一个有效的持续时间。否则我会从 API.

中捕获运行时异常和 return