問題:
我下載的視頻文件不能從任何播放器上播放,更別說我的應用程序的VideoView,但它從URL中很好地扮演成VideoView。下載的視頻文件無法在Android的播放
什麼DONE:
我下載a video file,如果它不是在外部存儲,否則直接從網址到VideoView播放。
代碼的VideoView部分是這樣的:
final VideoView vvPlayer = (VideoView) findViewById(R.id.vvPlayer);
MediaController mc = new MediaController(MainActivity.this);
mc.setAnchorView(vvPlayer);
vvPlayer.setMediaController(mc);
if (videoFile.exists()) {
// vvPlayer.setVideoURI(Uri.fromFile(videoFile)); <-- Also Tried :(
vvPlayer.setVideoPath(videoFile.getAbsolutePath());
Toast.makeText(this, "Playing from local ...", Toast.LENGTH_SHORT).show();
} else {
vvPlayer.setVideoPath(VIDEO_PATH);
Toast.makeText(this, "Playing online & caching ...", Toast.LENGTH_SHORT).show();
downloadVideoFile();
}
的芯核部,即,downloadVideoFile()
方法的的AsyncTask的the doInBackground()
返回文件的內容作爲使用以下代碼的字符串:
@Override
protected String doInBackground(Void... params) {
URLConnection conn;
try {
URL httpFileUrl = new URL(fileUrl);
conn = httpFileUrl.openConnection();
conn.connect();
} catch (IOException e) {
e.printStackTrace();
return null;
}
Log.d(TAG, "Connection opened");
InputStream inputStream;
try {
inputStream = new BufferedInputStream(conn.getInputStream(), 4096);
} catch (IOException e) {
e.printStackTrace();
return null;
}
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
int responseLen = 0;
StringBuilder stringBuilder = new StringBuilder();
String responseStr;
try {
while ((responseStr = bufferedReader.readLine()) != null) {
// Log.i(TAG, "Response read: " + responseStr);
stringBuilder.append(responseStr.trim());
// ...my progress-bar related codes
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
responseStr = stringBuilder.toString();
return responseStr;
}
獲取文件的內容後,我平凡保存使用下面的代碼在那些文件:
try {
if (!APP_DIRECTORY.exists())
APP_DIRECTORY.mkdirs();
if (videoFile.createNewFile())
Log.d(TAG, "Vide-file newly created");
FileOutputStream fos = new FileOutputStream(videoFile);
fos.write(fileContent.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
Log.d(TAG, "Exception for new creation of videoFile");
e.printStackTrace();
}
最終結果是一個8.81 MB的文件,無法用任何視頻播放器打開爲視頻文件,更不用說我嘗試過的VideoView。
可能是我想的東西像編解碼器,編碼甚至簡單文件保存一部分?
不,StringBuilder無法處理二進制視頻數據。您不應該使用針對文本數據進行調整的readLine()。一旦從網絡獲得數據,就直接將數據寫入FileOutputStream。不要將其聚合在內存中:視頻可能包含比RAM更多的字節。 –