Search code examples
phpandroidandroid-mediaplayerduration

mediaplayer getduration returns 0 only in my server files


i'm trying to get the audio file duration from my server using media player

MediaPlayer mp = new MediaPlayer();
    try {
        mp.reset();
        mp.setDataSource("link here");
        mp.prepare();

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


    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            Log.e("time",mp.getDuration()+" ..");
        }
    });

when i put my server file link , it always return 0 but when i use another link from the web it gives me the right duration

do i need to do some configuration for that ?


Solution

  • If you cannot get duration of an audio link from you server, then you can try this library

    https://github.com/wseemann/FFmpegMediaMetadataRetriever

    To retrieve meta data (including duration) from an input media file.

    First write a method to get duration.

    private int getDurationInMilliseconds(String path) {
        FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
        mmr.setDataSource(path);
        int duration = Integer.parseInt(mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION));
        mmr.release();
        return duration;
    }
    

    Then change your code

    final String path = "http://dleelbaha.com/fayziah/download/sound/1536950612.mp3";
    final MediaPlayer mp = new MediaPlayer();
    try {
        mp.reset();
        mp.setDataSource(path);
        mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            int duration = mp.getDuration();
            if (duration <= 0) {
                duration = getDurationInMilliseconds(path);
            }
            Log.i("time", duration + " ms");
        }
    });