我正在以编程方式从用户提供的URL下载音频文件MP3 / OGG。我还将继续将下载的文件设置为铃声/闹钟铃声。但是,我需要以编程方式验证下载的文件是否是有效的MP3 / OGG文件并且可以播放。我可以通过哪种方式确保已下载的文件是有效的MP3 / OGG文件,而不是伪URL的垃圾邮件头。
我正在使用的代码:
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);
}
}
答案 0 :(得分:1)
您可以检查下载流的结束,如果它被调用,它是一个指示,您的文件是否已完整下载。 如果它适合你,接受这个答案? 谢谢
答案 1 :(得分:1)
我通过使用MediaMetadataRetriever classe的API" extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)"解决了这个问题。如果它是有效的mp3 / ogg文件,则返回有效持续时间。否则,我会捕获运行时异常并从我的API返回。