2012-12-04 98 views
1

我試圖通過intent(默認媒體播放器)播放遠程視頻文件,但我也希望在流式傳輸時將其保存在本地。我正在嘗試下面的代碼來保存本地的視頻文件在工作正常的蒸汽。現在我想立即開始我的意圖,但是當意圖開始時,我收到錯誤「Sorry this video can not be played」。請注意,如果我在完成流式傳輸時(downloadedSize==totalSize)將意圖代碼移到此方法結束時,那麼它可以正常工作,但我想在播放時同時播放。任何幫助?視頻文件無法播放流式傳輸

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; 

    } 

回答

0

我認爲這個問題是在這一行:

i.setDataAndType(Uri.parse(file.getPath()),"video/*"); 

你傳遞你的本地文件的意圖,但這是尚未下載的一個。我想你應該使用URL流視頻和內容存儲在文件

// Use the url of the remote location 
i.setDataAndType(Uri.parse(Url),"video/*"); 
// Also, try to use lowercase for variables e.g. url vs Url 

這樣,你是流遠程URL,並保存內容到本地文件。 我可能會誤解代碼,但我會先看看那個