Android 获取音频时间【附代码】

今天爱分享给大家带来Android 获取音频时间【附代码】,希望能够帮助到大家。
0.媒体库查找


  String SELECTION = MediaStore.Audio.AudioColumns.SIZE + " >= ? AND " + MediaStore.Audio.AudioColumns.DURATION + " >= ?";

  long filterSize = 100* 1024L;
  long filterTime =100* 1000L;

   Cursor cursor = context.getContentResolver().query(
        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
        new String[]{
                BaseColumns._ID,
                MediaStore.Audio.AudioColumns.IS_MUSIC,
                MediaStore.Audio.AudioColumns.TITLE,
                MediaStore.Audio.AudioColumns.ARTIST,
                MediaStore.Audio.AudioColumns.ALBUM,
                MediaStore.Audio.AudioColumns.ALBUM_ID,
                MediaStore.Audio.AudioColumns.DATA,
                MediaStore.Audio.AudioColumns.DISPLAY_NAME,
                MediaStore.Audio.AudioColumns.SIZE,
                MediaStore.Audio.AudioColumns.DURATION
        },
        SELECTION,
        new String[]{
                String.valueOf(filterSize),
                String.valueOf(filterTime)
        },
        MediaStore.Audio.Media.DEFAULT_SORT_ORDER);



然后操作cursor.
对于不在媒体库中的需要根据文件路径来:
1.MediaPlayer根据url/path


MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.getDuration(); 



2.使用MediaMetadataRetriever,根据path可以获取音视频


  /**
 * get Local video and audio duration
 *
 * @return
 */
public static int getLocalVideoDuration(String videoPath) {
    //时长(毫秒)
    int duration;
    try {
        MediaMetadataRetriever mmr = new  MediaMetadataRetriever();
        mmr.setDataSource(videoPath);
        duration = Integer.parseInt(mmr.extractMetadata
                (MediaMetadataRetriever.METADATA_KEY_DURATION))/1000;
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
    return duration;
}



人已赞赏
安卓

MediaPlayer stop之后再次start播放失败【解决方法】

2020-12-23 11:43:31

安卓

Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.3.72【解决方法】

2020-12-23 14:06:00

'); })();