2015-01-15 1 views
0

enter image description here как я могу установить видео с url в локальной памяти и играть там в android? Можете ли вы поделиться примерным кодом об этом? Я попытался, как показано ниже, но я получаю ошибку «Sorr, это видео не играл» Видео не играл, но код установки для видео файла .I может увидеть это «File Explorer»установить видео в локальной памяти и сыграть там в android

public class VideoSaveSDCARD extends Activity { 

    private VideoView vView; 

    private static final String TAG = "UpdaterService"; 
    File SDCardRoot; 
    Handler asyncHandler = new Handler(); 
    String videoLink = "http://hurriyettv.cubecdn.net/2014/11/19/htv_99710_240p.mp4"; 
    String name = "blaa.mp4"; 
    private Updater updater; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
       .permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
     SDCardRoot = new File(getFilesDir() + "/videos"); 

     File[] videos = SDCardRoot.listFiles(); 

     vView = (VideoView) findViewById(R.id.vview); 

     try { 

      String[] fileArray = new String[videos.length]; 
      for (int i = 1; i < 2; i++) { 
       fileArray[i] = videos[i].getName(); 

       Log.i("@Tag:file[1]", "" + fileArray[i]); 

       vView.requestFocus(); 

       vView.setVideoPath("" + fileArray[i]); 

       vView.start(); 

       // MediaPlayer pl = new MediaPlayer(); 
       // pl.setDataSource(fi.getFD()); 
       // pl.prepare(); 
       // pl.start(); 
       // 
      } 
     } catch (Exception e) { 
      // TODO: handle exception 
     } 

     /* 
     * Log.i("fileeee", "" + videos[1]); 
     * 
     * vView = (VideoView) findViewById(R.id.vview); 
     * 
     * // use this to get touch events vView.requestFocus(); 
     * 
     * // load video from SD card vView.setVideoPath(
     * "/data/data/com.example.downlaodvideo/files/videos/blaa.mp4"); 
     * 
     * // enable this if you want to enable video controllers, such as pause 
     * // and forward 
     * 
     * // plays the movie vView.start(); 
     */ 

     File SDCardRoot = new File(VideoSaveSDCARD.this.getFilesDir() + "/" 
       + "videos"); 

     if (!SDCardRoot.exists()) { 
      SDCardRoot.mkdir(); 
     } 
     // deleteDirectory(SDCardRoot); 

     updater = new Updater(); 
     updater.start(); 
    } 

    class Updater extends Thread { 

     @Override 
     public void run() { 
      super.run(); 
      downloadFiles(videoLink, name); 
     } 
    } 

    synchronized boolean downloadFiles(String link, String videoName) { 
     try { 
      URL url = new URL(link); // you can write here any link 

      long startTime = System.currentTimeMillis(); 
      Log.d("VideoManager", "download begining"); 
      Log.d("VideoManager", "download url:" + url); 
      Log.d("VideoManager", "downloaded file name:" + videoName); 
      /* Open a connection to that URL. */ 
      URLConnection ucon = url.openConnection(); 

      /* 
      * Define InputStreams to read from the URLConnection. 
      */ 
      InputStream is = ucon.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 

      /* 
      * Read bytes to the Buffer until there is nothing more to read(-1). 
      */ 
      ByteArrayBuffer baf = new ByteArrayBuffer(50); 
      int current = 0; 
      while ((current = bis.read()) != -1) { 
       baf.append((byte) current); 
      } 

      /* Convert the Bytes read to a String. */ 
      FileOutputStream fos = new FileOutputStream(new File(SDCardRoot, 
        videoName)); 
      fos.write(baf.toByteArray()); 
      fos.close(); 
      Log.d("VideoManager", 
        "download ready in" 
          + ((System.currentTimeMillis() - startTime)/1000) 
          + " sec"); 
      return true; 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return false; 
    } 

    public String getDataFromPortal(String remoteUrl, String myString) { 
     String data = null; 
     DefaultHttpClient httpclient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(remoteUrl + myString); 

     try { 
      HttpResponse response1 = httpclient.execute(httpGet); 
      InputStream is = response1.getEntity().getContent(); 

      data = getStringFromInputStream(is); 
      return data; 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      Log.d(TAG, "................internet yok catch 1"); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      Log.d(TAG, "................internet yok catch 2"); 
      e.printStackTrace(); 
     } 

     // The underlying HTTP connection is still held by the response 
     // object 
     // to allow the response content to be streamed directly from the 
     // network socket. 
     // In order to ensure correct deallocation of system resources 
     // the user MUST either fully consume the response content or abort 
     // request 
     // execution by calling HttpGet#releaseConnection(). 
     return data; 
    } 

    private String getStringFromInputStream(InputStream is) { 

     BufferedReader br = null; 
     StringBuilder sb = new StringBuilder(); 

     String line; 
     try { 

      br = new BufferedReader(new InputStreamReader(is)); 
      while ((line = br.readLine()) != null) { 
       sb.append(line); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (br != null) { 
       try { 
        br.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

     return sb.toString(); 

    } 

    public static boolean deleteDirectory(File path) { 
     if (path.exists()) { 
      File[] files = path.listFiles(); 
      if (files == null) { 
       return true; 
      } 
      for (int i = 0; i < files.length; i++) { 
       if (files[i].isDirectory()) { 
        deleteDirectory(files[i]); 
       } else { 
        files[i].delete(); 
       } 
      } 
     } 
     return (path.delete()); 
    } 

} 
+0

Где код игрока? –

+0

String [] fileArray = new String [videos.length]; для (int i = 1; i <2; i ++) { fileArray [i] = videos [i] .getName(); Log.i ("@ Тег: файл [1]", "" + fileArray [i]); vView.requestFocus(); vView.setVideoPath ("" + fileArray [i]); vView.start(); } – Diego

+0

Re Редактировать свой вопрос с полным кодом –

ответ

0
public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      Log.d("on create","on create"); 
      setContentView(R.layout.activity_main); 
      new Asyntask().execute(); 

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
        .permitAll().build(); 
      StrictMode.setThreadPolicy(policy); 
      SDCardRoot = new File("/sdcard/videos"); 
      Log.d("SDCARDGGHGHg",""+SDCardRoot); 
      File[] videos = SDCardRoot.listFiles(); 
      //Log.d("Videos array ",""+videos[0].getName()); 
      vView = (VideoView) findViewById(R.id.vview); 
      Log.d("before try cathc","testing"); 
File SDCardRoot = new File("/sdcard/videos"); 
     Log.d("SDCardRoot",""+SDCardRoot); 

     if (!SDCardRoot.exists()) { 
      SDCardRoot.mkdir(); 
     } 
} 
class Asyntask extends AsyncTask<Void,Void,Void> 
    { 

     @Override 
     protected Void doInBackground(Void... params) { 
      // TODO Auto-generated method stub 
      Log.d("In background","in background"); 
      URL url; 
      try { 
       url = new URL(videoLink); 
       long startTime = System.currentTimeMillis(); 
       Log.d("VideoManager", "download begining"); 
       Log.d("VideoManager", "download url:" + url); 
       Log.d("VideoManager", "downloaded file name:" + name); 
       /* Open a connection to that URL. */ 
       URLConnection ucon = url.openConnection(); 
       InputStream is = ucon.getInputStream(); 
       BufferedInputStream bis = new BufferedInputStream(is); 
       ByteArrayBuffer baf = new ByteArrayBuffer(50); 
       int current = 0; 
       while ((current = bis.read()) != -1) { 
        baf.append((byte) current); 
       } 
       FileOutputStream fos; 

        fos = new FileOutputStream(new File(SDCardRoot, 
          name)); 
        fos.write(baf.toByteArray()); 
        fos.close(); 

      } catch (MalformedURLException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
      catch (Exception e) { 
       // TODO: handle exception 
      } 
      return null; 


     } 

     @Override 
     protected void onPostExecute(Void result) { 
      // TODO Auto-generated method stub 
      Log.d("In post","in post"); 
      vView.setVideoPath(SDCardRoot+"/blaa.mp4"); 

      vView.start(); 
      Log.d("android","post execute"); 
      super.onPostExecute(result); 
     } 


    } 

Это будет работать ваш код.

+0

Я думаю, что у меня другая проблема, ваш код верен, но когда я запускаю приложение, у меня появилась такая ошибка: «Не могу воспроизвести видео " – Diego

+0

Вы пробовали этот код .... потому что в моем случае я не получаю никаких ошибок, видео играет абсолютно нормально. –