2013-11-27 144 views
2

我需要對我的應用程序進行編程,以先從服務器下載視頻並在播放前保存到SD卡中。我在哪裏可以得到這個教程?在Android上播放視頻之前下載視頻VideoView

目前,我流視頻,但我不想這樣。

final VideoView videoView = (VideoView)rootView.findViewById(R.id.styleVideo); 
     videoView.setVideoURI(Uri.parse(videoPath)); 
     videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 

      public void onPrepared(MediaPlayer mp) { 
       videoView.setBackground(mScarfBuffer.getDrawable(position)); 
      } 
     }); 
     videoView.setMediaController(new MediaController(rootView.getContext())); 
     videoView.requestFocus(); 
     videoView.start(); 
+0

USSE HTTP方法的視頻來獲取視頻,並將其保存到SD卡 – r4jiv007

+0

@ r4jiv007請解釋更多的細節。 – user2412351

回答

1

使用下面的下載文件:

void downloadFile(){ 

    try { 
     URL url = new URL(dwnload_file_path); 
     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

     urlConnection.setRequestMethod("GET"); 
     urlConnection.setDoOutput(true); 

     //connect 
     urlConnection.connect(); 

     //set the path where we want to save the file   
     String SDCardRoot= Environment.getExternalStorageDirectory() ; 
     //create a new file, to save the downloaded file 
     File file = new File(SDCardRoot,"mydownloadmovie.mp4"); 

     FileOutputStream fileOutput = new FileOutputStream(file); 

     //Stream used for reading the data from the internet 
     InputStream inputStream = urlConnection.getInputStream(); 

     //this is the total size of the file which we are downloading 
     totalSize = urlConnection.getContentLength(); 


     //create a buffer... 
     byte[] buffer = new byte[1024]; 
     int bufferLength = 0; 

     while ((bufferLength = inputStream.read(buffer)) > 0) { 
      fileOutput.write(buffer, 0, bufferLength); 
      downloadedSize += bufferLength; 
       } 
     //close the output stream when complete // 
     fileOutput.close(); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    catch (Exception e) { 

    }  
} 

不要忘記到裏面的AsyncTask包裹。
然後使用MediaPlayer播放您下載的文件(現在是本地文件)。

+0

感謝您的回答,我會嘗試並更新結果。 :) – user2412351

+0

如何強制應用程序等待文件下載! - 因爲在運行AsyncTask下載後,該應用程序將立即使用該文件! – EsmaeelQash

+0

@EsmaeelQash你在onPostExecute()上做它嗎?如果您的AsyncTask()是正確的,則應在調用onPostExecute時完成文件下載。 –

0

此代碼下載和播放已完成

public class Testing extends AppCompatActivity { 
    VideoView videoView; 
MediaController mediaController; 

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_testing); 
     videoView = (VideoView) findViewById(R.id.vid258); 
     mediaController = new MediaController(this); 
// Enter Your Server Link 
final DownloadTask downloadTask = new DownloadTask(Testing.this); 
     downloadTask.execute("http://codechair.com/video/1496139752333.mp4"); 
}); 
} 
private class DownloadTask extends AsyncTask<String, Integer, String> { 

     private Context context; 
     private PowerManager.WakeLock mWakeLock; 

     public DownloadTask(Context context) { 
      this.context = context; 
     } 

     @Override 
     protected String doInBackground(String... sUrl) { 
      InputStream input = null; 
      OutputStream output = null; 
      HttpURLConnection connection = null; 
      try { 
       URL url = new URL(sUrl[0]); 
       connection = (HttpURLConnection) url.openConnection(); 
       connection.connect(); 

       // expect HTTP 200 OK, so we don't mistakenly save error report 
       // instead of the file 
       if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
        return "Server returned HTTP " + connection.getResponseCode() 
          + " " + connection.getResponseMessage(); 
       } 

       // this will be useful to display download percentage 
       // might be -1: server did not report the length 
       int fileLength = connection.getContentLength(); 

       // download the file 
       input = connection.getInputStream(); 
       output = new FileOutputStream("/sdcard/file_name.mp4"); 

       byte data[] = new byte[4096]; 
       Log.d("Orignalvalu1",String.valueOf(new byte[4096])); 
       long total = 0; 
       int count; 
       while ((count = input.read(data)) != -1) { 
        Log.d("Orignalvalu1",String.valueOf(input.read(data))); 
        // allow canceling with back button 
        if (isCancelled()) { 
         input.close(); 
         return null; 
        } 
        total += count; 
        Log.d("Orignalvalu2",String.valueOf(total)); 
        // publishing the progress.... 
        if (fileLength > 0) // only if total length is known 
         publishProgress((int) (total * 100/fileLength)); 
        output.write(data, 0, count); 
       } 
      } catch (Exception e) { 
       return e.toString(); 
      } finally { 
       try { 
        if (output != null) 
         output.close(); 
        if (input != null) 
         input.close(); 
       } catch (IOException ignored) { 
       } 

       if (connection != null) 
        connection.disconnect(); 
      } 
      return null; 
     } 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // take CPU lock to prevent CPU from going off if the user 
      // presses the power button during download 
      PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 
      mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
        getClass().getName()); 
      mWakeLock.acquire(); 
      mProgressDialog.show(); 
     } 

     @Override 
     protected void onProgressUpdate(Integer... progress) { 
      super.onProgressUpdate(progress); 
      // if we get here, length is known, now set indeterminate to false 
      mProgressDialog.setIndeterminate(false); 
      mProgressDialog.setMax(100); 
      mProgressDialog.setProgress(progress[0]); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      mWakeLock.release(); 
      mProgressDialog.dismiss(); 
      if (result != null) 
       Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show(); 
      else 
       Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show(); 
      videoView.setVideoPath("/storage/emulated/0/file_name.mp4"); 
      videoView.setMediaController(mediaController); 
      videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 
       @Override 
       public void onPrepared(MediaPlayer mp) { 
        mp.setLooping(true); 
       } 
      }); 
      videoView.requestFocus(); 
      videoView.start(); 
     } 
    }