Example #1
0
 private Bitmap createVideoThumbnail(String url) {
   Bitmap bitmap = null;
   MediaMetadataRetriever retriever = new MediaMetadataRetriever();
   int kind = MediaStore.Video.Thumbnails.MINI_KIND;
   try {
     if (Build.VERSION.SDK_INT >= 14) {
       retriever.setDataSource(url, new HashMap<String, String>());
     } else {
       retriever.setDataSource(url);
     }
     bitmap = retriever.getFrameAtTime();
   } catch (IllegalArgumentException ex) {
     // Assume this is a corrupt video file
   } catch (RuntimeException ex) {
     // Assume this is a corrupt video file.
   } finally {
     try {
       retriever.release();
     } catch (RuntimeException ex) {
       // Ignore failures while cleaning up.
     }
   }
   if (kind == MediaStore.Images.Thumbnails.MICRO_KIND && bitmap != null) {
     bitmap =
         ThumbnailUtils.extractThumbnail(bitmap, 10, 10, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
   }
   return bitmap;
 }
Example #2
0
  private static Bitmap createVideoThumbnailBitmap(
      String filePath, FileDescriptor fd, int targetWidth) {
    Bitmap bitmap = null;
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
      if (filePath != null) {
        retriever.setDataSource(filePath);
      } else {
        retriever.setDataSource(fd);
      }
      bitmap = retriever.getFrameAtTime(-1);
    } catch (IllegalArgumentException ex) {
      // Assume this is a corrupt video file
    } catch (RuntimeException ex) {
      // Assume this is a corrupt video file.
    } finally {
      try {
        retriever.release();
      } catch (RuntimeException ex) {
        // Ignore failures while cleaning up.
      }
    }
    if (bitmap == null) return null;

    // Scale down the bitmap if it is bigger than we need.
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    if (width > targetWidth) {
      float scale = (float) targetWidth / width;
      int w = Math.round(scale * width);
      int h = Math.round(scale * height);
      bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
    }
    return bitmap;
  }
 private int getDuration() {
   Movie movie = mItems.get(mCurrentItem);
   MediaMetadataRetriever mmr = new MediaMetadataRetriever();
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
     mmr.setDataSource(movie.getVideoUrl(), new HashMap<String, String>());
   } else {
     mmr.setDataSource(movie.getVideoUrl());
   }
   String time = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
   long duration = Long.parseLong(time);
   return (int) duration;
 }
Example #4
0
 public UFile(String path) {
   try {
     file = new File(path);
     this.path = file.getPath();
     this.name = file.getName();
     size = file.length();
     thumbNail = null;
     if (isMovie()) {
       MediaMetadataRetriever retriever = new MediaMetadataRetriever();
       retriever.setDataSource(path);
       String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
       movieLength = Long.parseLong(time);
       thumbNail =
           ThumbnailUtils.createVideoThumbnail(
               path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
     } else if (isImage()) {
       Bitmap temp = BitmapFactory.decodeFile(file.getPath());
       float scale = context.getResources().getDisplayMetrics().densityDpi / 160f;
       thumbNail =
           ThumbnailUtils.extractThumbnail(temp, (int) (50f * scale), (int) (50f * scale));
     } else if (file.isDirectory()) {
       thumbNail = BitmapFactory.decodeResource(null, R.mipmap.docu);
     }
   } catch (Exception e) {
     file = null;
   }
 }
 /**
  * @param sourceFile
  * @throws IOException
  */
 private final void handlePrepare(final String source_file) throws IOException {
   if (DEBUG) Log.v(TAG, "handlePrepare:");
   synchronized (mSync) {
     if (mState != STATE_STOP) {
       throw new RuntimeException("invalid state:" + mState);
     }
   }
   final File src = new File(source_file);
   if (TextUtils.isEmpty(source_file) || !src.canRead()) {
     throw new FileNotFoundException("Unable to read " + source_file);
   }
   mVideoTrackIndex = -1;
   mMetadata = new MediaMetadataRetriever();
   mMetadata.setDataSource(source_file);
   updateMovieInfo();
   // preparation for video playback
   mVideoTrackIndex = internal_prepare_video(source_file);
   if (mVideoTrackIndex < 0) {
     throw new RuntimeException("No video track found in " + source_file);
   }
   synchronized (mSync) {
     mState = STATE_PREPARED;
   }
   mCallback.onPrepared();
 }
 public Bitmap getFrameAtTime(long time) {
   if (retriever == null) {
     retriever = new MediaMetadataRetriever();
     retriever.setDataSource(filePath);
   }
   return retriever.getFrameAtTime(time * 1000, MediaMetadataRetriever.OPTION_CLOSEST);
 }
 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
   MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
   try {
     metadataRetriever.setDataSource(file.getAbsolutePath());
   } catch (Exception e) {
     throw new NotAVideoFile();
   }
   String hasVideo =
       metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
   if (hasVideo == null) {
     throw new NotAVideoFile();
   }
   int rotation = extractRotationFromMediaRetriever(metadataRetriever);
   boolean rotated = rotation == 90 || rotation == 270;
   int height;
   try {
     String h =
         metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
     height = Integer.parseInt(h);
   } catch (Exception e) {
     height = -1;
   }
   int width;
   try {
     String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
     width = Integer.parseInt(w);
   } catch (Exception e) {
     width = -1;
   }
   metadataRetriever.release();
   Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
   return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
 }
  /**
   * Sets the data source as a content Uri. Call this method before the rest of the methods in this
   * class. This method may be time-consuming.
   *
   * @param context the Context to use when resolving the Uri
   * @param uri the Content URI of the data you want to play
   * @throws IllegalArgumentException if the Uri is invalid
   * @throws SecurityException if the Uri cannot be used due to lack of permission.
   */
  public void setDataSource(Context context, Uri uri)
      throws IllegalArgumentException, SecurityException {
    if (uri == null) {
      throw new IllegalArgumentException();
    }

    String scheme = uri.getScheme();
    if (scheme == null || scheme.equals("file")) {
      setDataSource(uri.getPath());
      return;
    }

    AssetFileDescriptor fd = null;
    try {
      ContentResolver resolver = context.getContentResolver();
      try {
        fd = resolver.openAssetFileDescriptor(uri, "r");
      } catch (FileNotFoundException e) {
        throw new IllegalArgumentException();
      }
      if (fd == null) {
        throw new IllegalArgumentException();
      }
      FileDescriptor descriptor = fd.getFileDescriptor();
      if (!descriptor.valid()) {
        throw new IllegalArgumentException();
      }
      // Note: using getDeclaredLength so that our behavior is the same
      // as previous versions when the content provider is returning
      // a full file.
      if (fd.getDeclaredLength() < 0) {
        setDataSource(descriptor);
      } else {
        setDataSource(descriptor, fd.getStartOffset(), fd.getDeclaredLength());
      }
      return;
    } catch (SecurityException ex) {
    } finally {
      try {
        if (fd != null) {
          fd.close();
        }
      } catch (IOException ioEx) {
      }
    }
    setDataSource(uri.toString());
  }
 public static long getVideoDurationInMillis(String videoFile) {
   MediaMetadataRetriever retriever = new MediaMetadataRetriever();
   retriever.setDataSource(videoFile);
   String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
   long timeInmillisec = Long.parseLong(time);
   retriever.release();
   return timeInmillisec;
 }
Example #10
0
 /**
  * 获取本地音乐缩略图的方法
  *
  * @param filePath
  * @return
  */
 @SuppressLint("NewApi")
 public static Bitmap getLocalMusicBitmap(String filePath) {
   Bitmap bitmap = null;
   MediaMetadataRetriever mmr = new MediaMetadataRetriever();
   mmr.setDataSource(filePath);
   bitmap = Bytes2Bimap(mmr.getEmbeddedPicture());
   return bitmap;
 }
 public void setVideoPath(String path) {
   mediaMetadataRetriever = new MediaMetadataRetriever();
   try {
     mediaMetadataRetriever.setDataSource(path);
     String duration =
         mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
     videoLength = Long.parseLong(duration);
   } catch (Exception e) {
     FileLog.e("tmessages", e);
   }
 }
  public static void setAlbumArt(ImageView imageview, String file, boolean compress) {

    String albumArtpath = allSongsList.getAlbumArt(file);

    if (albumArtpath != null) {
      File albumArtFile = new File(albumArtpath);
      Bitmap bm = null;
      InputStream iStream1 = null;
      InputStream iStream2 = null;

      try {

        iStream1 = new BufferedInputStream(new FileInputStream(albumArtFile));
        if (!compress) {
          bm = BitmapFactory.decodeStream(iStream1);
        } else {
          iStream2 = new BufferedInputStream(new FileInputStream(albumArtFile));
          bm = decodeFile2(iStream1, iStream2, 100, 100);
        }
        imageview.setImageBitmap(bm);

      } catch (FileNotFoundException e) {

        MediaMetadataRetriever md = new MediaMetadataRetriever();
        md.setDataSource(file);
        byte[] art = md.getEmbeddedPicture();
        if (art != null) {

          iStream1 = new ByteArrayInputStream(md.getEmbeddedPicture());

          if (!compress) {

            bm = BitmapFactory.decodeStream(iStream1);
          } else {
            iStream2 = new ByteArrayInputStream(md.getEmbeddedPicture());
            bm = decodeFile2(iStream1, iStream2, 100, 100);
          }
          imageview.setImageBitmap(bm);
        } else {
          imageview.setImageDrawable(
              imageview
                  .getContext()
                  .getResources()
                  .getDrawable(R.drawable.ic_expandplayer_placeholder));
        }
      }
    } else {
      imageview.setImageDrawable(
          imageview
              .getContext()
              .getResources()
              .getDrawable(R.drawable.ic_expandplayer_placeholder));
    }
  }
Example #13
0
 // @TargetApi(11)
 private void calculateDuration(ContentValues map) throws IOException {
   if (Utils.isGingerBreadMROrLater()) {
     File videoFile = fileFromResourceMap(map);
     MediaMetadataRetriever mmr = new MediaMetadataRetriever();
     mmr.setDataSource(videoFile.toString());
     String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
     if (!TextUtils.isEmpty(duration)) {
       map.put(Resources.DURATION, Integer.valueOf(duration));
     }
     mmr.release();
   }
 }
Example #14
0
  public static Bitmap getBitmap(Context context, int id, boolean isImage) {
    String filename = getDataFilepathForMedia(context.getContentResolver(), id, isImage);

    /* ttt_installer:remove_line */ Log.d(GTG.TAG, "Loading bitmap for " + filename);

    if (filename == null) return null;

    if (isImage) return new BitmapDrawable(context.getResources(), filename).getBitmap();

    MediaMetadataRetriever mmr = new MediaMetadataRetriever();
    mmr.setDataSource(filename);
    return mmr.getFrameAtTime();
  }
  // Verify result code, result data, and the duration.
  private int verify(CameraActivity activity, Uri uri) throws Exception {
    assertTrue(activity.isFinishing());
    assertEquals(Activity.RESULT_OK, activity.getResultCode());

    // Verify the video file
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(activity, uri);
    String duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    assertNotNull(duration);
    int durationValue = Integer.parseInt(duration);
    Log.v(TAG, "Video duration is " + durationValue);
    assertTrue(durationValue > 0);
    return durationValue;
  }
Example #16
0
 private void addSongToList(File file) {
   if (file.getName().endsWith(".mp3")) {
     DatabaseHandler db = new DatabaseHandler(Setting.this);
     String songName = file.getName().substring(0, (file.getName().length() - 4));
     String songPath = file.getPath();
     MediaMetadataRetriever media = new MediaMetadataRetriever();
     media.setDataSource(songPath);
     byte[] data = media.getEmbeddedPicture();
     String songArtist = media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
     String songAlbum = media.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
     media.release();
     db.addSongData(new SongData(songName, songPath, songArtist, songAlbum, data, 0));
     db.close();
   }
 }
  // two extra methods for async-loading of images
  public static Bitmap decodeAlbumArt(String file, boolean compress) {

    Bitmap toReturn = null;

    String albumArtpath = allSongsList.getAlbumArt(file);

    if (albumArtpath != null) {
      File albumArtFile = new File(albumArtpath);
      Bitmap bm = null;
      InputStream iStream1 = null;
      InputStream iStream2 = null;

      try {

        iStream1 = new BufferedInputStream(new FileInputStream(albumArtFile));
        if (!compress) {
          bm = BitmapFactory.decodeStream(iStream1);
        } else {
          iStream2 = new BufferedInputStream(new FileInputStream(albumArtFile));
          bm = decodeFile2(iStream1, iStream2, 100, 100);
        }

      } catch (FileNotFoundException e) {

        MediaMetadataRetriever md = new MediaMetadataRetriever();
        md.setDataSource(file);
        byte[] art = md.getEmbeddedPicture();
        if (art != null) {

          iStream1 = new ByteArrayInputStream(md.getEmbeddedPicture());

          if (!compress) {

            bm = BitmapFactory.decodeStream(iStream1);
          } else {
            iStream2 = new ByteArrayInputStream(md.getEmbeddedPicture());
            bm = decodeFile2(iStream1, iStream2, 100, 100);
          }
        }
      }
      toReturn = bm;
    }
    return toReturn;
  }
 private Bitmap getVideoPreview(File file, int size) {
   MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
   Bitmap frame;
   try {
     metadataRetriever.setDataSource(file.getAbsolutePath());
     frame = metadataRetriever.getFrameAtTime(0);
     metadataRetriever.release();
     frame = resize(frame, size);
   } catch (IllegalArgumentException | NullPointerException e) {
     frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
     frame.eraseColor(0xff000000);
   }
   Canvas canvas = new Canvas(frame);
   Bitmap play =
       BitmapFactory.decodeResource(mXmppConnectionService.getResources(), R.drawable.play_video);
   float x = (frame.getWidth() - play.getWidth()) / 2.0f;
   float y = (frame.getHeight() - play.getHeight()) / 2.0f;
   canvas.drawBitmap(play, x, y, null);
   return frame;
 }
Example #19
0
  /**
   * Returns a (possibly empty) Cursor for given file path
   *
   * @param path The path to the file to be queried
   * @return A new Cursor object
   */
  public static Cursor getCursorForFileQuery(String path) {
    MatrixCursor matrixCursor = new MatrixCursor(Song.FILLED_PROJECTION);
    MediaMetadataRetriever data = new MediaMetadataRetriever();

    try {
      data.setDataSource(path);
    } catch (Exception e) {
      Log.w("VanillaMusic", "Failed to extract metadata from " + path);
    }

    String title = data.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
    String album = data.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
    String artist = data.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
    String duration = data.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);

    if (duration != null) { // looks like we will be able to play this file
      // Vanilla requires each file to be identified by its unique id in the media database.
      // However: This file is not in the database, so we are going to roll our own
      // using the negative crc32 sum of the path value. While this is not perfect
      // (the same file may be accessed using various paths) it's the fastest method
      // and far good enough.
      CRC32 crc = new CRC32();
      crc.update(path.getBytes());
      Long songId =
          (Long) (2 + crc.getValue())
              * -1; // must at least be -2 (-1 defines Song-Object to be empty)

      // Build minimal fake-database entry for this file
      Object[] objData = new Object[] {songId, path, "", "", "", 0, 0, 0, 0};

      if (title != null) objData[2] = title;
      if (album != null) objData[3] = album;
      if (artist != null) objData[4] = artist;
      if (duration != null) objData[7] = Long.parseLong(duration, 10);

      matrixCursor.addRow(objData);
    }

    return matrixCursor;
  }
Example #20
0
  private void initMediaDuration(Uri uri) throws MmsException {
    if (uri == null) {
      throw new IllegalArgumentException("Uri may not be null.");
    }

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    int duration = 0;
    try {
      retriever.setDataSource(mContext, uri);
      String dur = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
      if (dur != null) {
        duration = Integer.parseInt(dur);
      }
      mDuration = duration;
      Xlog.i(TAG, "Got audio duration:" + duration);
    } catch (Exception ex) {
      Xlog.e(TAG, "MediaMetadataRetriever failed to get duration for " + uri.getPath(), ex);
      throw new MmsException(ex);
    } finally {
      retriever.release();
    }
  }
    @Override
    public Bitmap getBitmap(int position) {
      MusicInfo musicInfo = (MusicInfo) getItem(position);

      MediaMetadataRetriever retriever = new MediaMetadataRetriever();
      retriever.setDataSource(mContext, musicInfo.getUri());

      byte[] albumArt = retriever.getEmbeddedPicture();

      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inSampleSize = 4; // 2의 배수

      Bitmap bitmap;
      if (null != albumArt) {
        bitmap = BitmapFactory.decodeByteArray(albumArt, 0, albumArt.length, options);
      } else {
        bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_no_image);
      }

      // id 로부터 bitmap 생성
      return bitmap;
    }
  public void sendVideo(Peer peer, String fullFilePath, String fileName) {
    try {
      MediaMetadataRetriever retriever = new MediaMetadataRetriever();
      retriever.setDataSource(fullFilePath);
      int duration =
          (int)
              (Long.parseLong(
                      retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION))
                  / 1000L);
      Bitmap img = retriever.getFrameAtTime(0);
      int width = img.getWidth();
      int height = img.getHeight();
      Bitmap smallThumb = ImageHelper.scaleFit(img, 90, 90);
      byte[] smallThumbData = ImageHelper.save(smallThumb);

      FastThumb thumb =
          new FastThumb(smallThumb.getWidth(), smallThumb.getHeight(), smallThumbData);

      sendVideo(peer, fileName, width, height, duration, thumb, fullFilePath);
    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
  private boolean RetrieverFile(String path, int nType) {
    nVideoW = 0;
    nVideoH = 0;
    // 取得影片寬高
    MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
    // --20150327-fix crash bug
    try {
      metaRetriever.setDataSource(path);
    } catch (Exception e) {
      e.printStackTrace();
      metaRetriever.release();
      Log.v(TAG, "PATH=" + path);
      Log.e(TAG, "MediaMetadataRetriever setDataSource error");
      return false;
    } // !--20150327-fix crash bug

    if (nType == 1) {
      String temp = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
      if (temp != null) {
        try {
          nVideoW = Integer.parseInt(temp);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      temp = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
      if (temp != null) {
        try {
          nVideoH = Integer.parseInt(temp);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    metaRetriever.release();
    return true;
  }
  public AlbumMetaData mediaMetaData(String file_path) {
    AlbumMetaData albumMetaData = new AlbumMetaData();
    try {
      if (mmr == null) {
        mmr = new MediaMetadataRetriever();
      }
      mmr.setDataSource(file_path);

      albumMetaData.file_path = file_path;
      albumMetaData.title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
      albumMetaData.album_artist =
          mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST);
      albumMetaData.artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
      albumMetaData.author = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR);
      albumMetaData.genre = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR);
      albumMetaData.duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
      // albumMetaData.album_art = mmr.getEmbeddedPicture();
    } catch (Exception ex) {
      Log.e("Error: ", "Unable to get meta data");
    }
    if (albumMetaData.file_path == null || albumMetaData.file_path.isEmpty())
      albumMetaData.file_path = "";
    if (albumMetaData.album_artist == null || albumMetaData.album_artist.isEmpty())
      albumMetaData.album_artist = "Unknown Album Artist";
    if (albumMetaData.title == null || albumMetaData.title.isEmpty())
      albumMetaData.title = "Unknown Title";
    if (albumMetaData.artist == null || albumMetaData.artist.isEmpty())
      albumMetaData.artist = "Unknown Artist";
    if (albumMetaData.author == null || albumMetaData.author.isEmpty())
      albumMetaData.author = "Unknown Author";
    if (albumMetaData.genre == null || albumMetaData.genre.isEmpty())
      albumMetaData.genre = "Unknown Genre";
    if (albumMetaData.duration == null || albumMetaData.duration.isEmpty())
      albumMetaData.duration = "-:-";
    mmr.release();
    return albumMetaData;
  }
    @Override
    public void run() {
      FeedMedia media = DBReader.getFeedMedia(DownloadService.this, request.getFeedfileId());
      if (media == null) {
        throw new IllegalStateException("Could not find downloaded media object in database");
      }
      boolean chaptersRead = false;
      media.setDownloaded(true);
      media.setFile_url(request.getDestination());

      // Get duration
      MediaMetadataRetriever mmr = null;
      try {
        mmr = new MediaMetadataRetriever();
        mmr.setDataSource(media.getFile_url());
        String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        media.setDuration(Integer.parseInt(durationStr));
        if (AppConfig.DEBUG) Log.d(TAG, "Duration of file is " + media.getDuration());
      } catch (NumberFormatException e) {
        e.printStackTrace();
      } catch (RuntimeException e) {
        e.printStackTrace();
      } finally {
        if (mmr != null) {
          mmr.release();
        }
      }

      if (media.getItem().getChapters() == null) {
        ChapterUtils.loadChaptersFromFileUrl(media);
        if (media.getItem().getChapters() != null) {
          chaptersRead = true;
        }
      }

      try {
        if (chaptersRead) {
          DBWriter.setFeedItem(DownloadService.this, media.getItem()).get();
        }
        DBWriter.setFeedMedia(DownloadService.this, media).get();
        if (!DBTasks.isInQueue(DownloadService.this, media.getItem().getId())) {
          DBWriter.addQueueItem(DownloadService.this, media.getItem().getId()).get();
        }
      } catch (ExecutionException e) {
        e.printStackTrace();
        status =
            new DownloadStatus(
                media,
                media.getEpisodeTitle(),
                DownloadError.ERROR_DB_ACCESS_ERROR,
                false,
                e.getMessage());
      } catch (InterruptedException e) {
        e.printStackTrace();
        status =
            new DownloadStatus(
                media,
                media.getEpisodeTitle(),
                DownloadError.ERROR_DB_ACCESS_ERROR,
                false,
                e.getMessage());
      }

      saveDownloadStatus(status);
      sendDownloadHandledIntent();

      numberOfDownloads.decrementAndGet();
      queryDownloadsAsync();
    }
Example #26
0
  private void CheckDir(String src) {
    // http://www.exampledepot.com/egs/java.io/GetFiles.html

    File rootNode = new File(src);
    boolean folderHasAlbumArt = false;

    try {
      if (rootNode.list(hasAlbumArt).length > 0) {
        folderHasAlbumArt = true;
      }

      for (String mp3 : rootNode.list(isMP3)) {
        metaDataReader.setDataSource(src + mp3);

        title = metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);

        String preFormat =
            metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER);
        String postFormat = "0";
        String item;
        boolean passed = false;

        if (preFormat != null && preFormat != "") {
          for (int i = 0; i < preFormat.length(); i++) {
            item = preFormat.substring(i, i + 1);

            if (item != "/" && passed != true) {
              postFormat = postFormat + item;
            } else {
              passed = true;
            }
          }

          try {
            number = Integer.parseInt(postFormat);
          } catch (NumberFormatException e) {
            // TODO fill
          }
        } else {
          number = 0;
        }

        artist = metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
        album = metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
        length =
            Double.parseDouble(
                metaDataReader.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));

        if (title == null) {
          title = "Unknown";
        }

        if (artist == null) {
          artist = "Unknown";
        }

        if (album == null) {
          album = "Unknown";
        }

        Track t = new Track(trackCount, title, number, artist, album, length, src + mp3);

        t.SetAlbumArt(folderHasAlbumArt);
        t.SetRootSrc(src);

        AddTrack(t);

        trackCount++;
      }

      for (String dir : rootNode.list(isDIR)) {
        CheckDir(src + dir + "/");
      }
    } catch (NullPointerException e) {
      // Probably No SD-Card
      Log.v(preferences.GetTag(), e.getMessage());
    }
  }
 /**
  * Sets the data source (FileDescriptor) to use. It is the caller's responsibility to close the
  * file descriptor. It is safe to do so as soon as this call returns. Call this method before the
  * rest of the methods in this class. This method may be time-consuming.
  *
  * @param fd the FileDescriptor for the file you want to play
  * @throws IllegalArgumentException if the FileDescriptor is invalid
  */
 public void setDataSource(FileDescriptor fd) throws IllegalArgumentException {
   // intentionally less than LONG_MAX
   setDataSource(fd, 0, 0x7ffffffffffffffL);
 }
Example #28
0
 @SuppressLint("NewApi")
 public static Bitmap getLocalVideoBitmap(String filePath) {
   MediaMetadataRetriever mmr = new MediaMetadataRetriever();
   mmr.setDataSource(filePath);
   return mmr.getFrameAtTime();
 }
Example #29
0
  public void displaySongInfo(final MusicDirectory.Entry song) {
    Integer bitrate = null;
    String format = null;
    long size = 0;
    try {
      DownloadFile downloadFile = new DownloadFile(SubsonicTabActivity.this, song, false);
      File file = downloadFile.getCompleteFile();
      if (file.exists()) {
        MediaMetadataRetriever metadata = new MediaMetadataRetriever();
        metadata.setDataSource(file.getAbsolutePath());
        String tmp = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);
        bitrate = Integer.parseInt((tmp != null) ? tmp : "0") / 1000;
        format = FileUtil.getExtension(file.getName());
        size = file.length();

        if (Util.isOffline(SubsonicTabActivity.this)) {
          song.setGenre(metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE));
          String year = metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_YEAR);
          song.setYear(Integer.parseInt((year != null) ? year : "0"));
        }
      }
    } catch (Exception e) {
      Log.i(TAG, "Device doesn't properly support MediaMetadataRetreiver");
    }

    String msg = "";
    if (!song.isVideo()) {
      msg += "Artist: " + song.getArtist() + "\nAlbum: " + song.getAlbum();
    }
    if (song.getTrack() != null && song.getTrack() != 0) {
      msg += "\nTrack: " + song.getTrack();
    }
    if (song.getGenre() != null && !"".equals(song.getGenre())) {
      msg += "\nGenre: " + song.getGenre();
    }
    if (song.getYear() != null && song.getYear() != 0) {
      msg += "\nYear: " + song.getYear();
    }
    if (!Util.isOffline(SubsonicTabActivity.this)) {
      msg += "\nServer Format: " + song.getSuffix();
      if (song.getBitRate() != null && song.getBitRate() != 0) {
        msg += "\nServer Bitrate: " + song.getBitRate() + " kpbs";
      }
    }
    if (format != null && !"".equals(format)) {
      msg += "\nCached Format: " + format;
    }
    if (bitrate != null && bitrate != 0) {
      msg += "\nCached Bitrate: " + bitrate + " kpbs";
    }
    if (size != 0) {
      msg += "\nSize: " + Util.formatBytes(size);
    }
    if (song.getDuration() != null && song.getDuration() != 0) {
      msg += "\nLength: " + Util.formatDuration(song.getDuration());
    }

    new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(song.getTitle())
        .setMessage(msg)
        .show();
  }