I am trying to play a remote video file through intent(default media player) but I also want to save it locally while it is being streamed. I am trying following code to save the steam locally in a video file which is working fine. Now I want to start my intent as soon as the file is being streamed but when intent is started I get the error “Sorry this video can not be played“. Note that if I move the intent code to end of this method when streaming is complete( when downloadedSize==totalSize) then it works fine but I want to play while being streamed at the same time. Any help?
public String DownloadVideo(String Url, String fileName)
{
String filepath=null;
try {
URL url = new URL(Url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,fileName);
if(file.createNewFile())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
int counter=0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
if(downloadedSize>2048)
{
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse(file.getPath()),"video/*");
startActivity(i);
}
downloadedSize += bufferLength;
counter++;
}
fileOutput.close();
if(downloadedSize==totalSize) {
filepath=file.getPath();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
filepath=null;
e.printStackTrace();
}
return filepath;
}
I think the problem is in this line:
Your passing the your local file to the Intent, but that is the one that has not been downloaded yet. I think you should use the Url to stream the video, and store the contents in file
That way, you are streaming the remote url, and saving the contents to your local file.
I may be misinterpreting the code, but I would start by looking into that