简体   繁体   中英

How to get the duration of an audio streaming from servers online

Collecting the total duration of an audio has become a problem for me. I am creating an activity that plays an audio from online, I use the android media player. Now the audio is able to play correctly, but the problem I am facing is allowing the seek bar progress accordingly with the audio. The seek bar is set correctly but i have seen that the getDuration returns 0 value. Below is what i have done.

public class AudioDetails extends AppCompatActivity
    implements MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {

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


    // Mediaplayer
    mp = new MediaPlayer();
    utils = new AudioUtilities();

    // Listeners
    songProgressBar.setOnSeekBarChangeListener(this); // Important
    mp.setOnCompletionListener(this); // Important



    // By default play first song
    playSong(0);

    /**
     * Play button click event
     * plays a song and changes button to pause image
     * pauses a song and changes button to play image
     * */
    btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check for already playing
            if(mp.isPlaying()){
                if(mp!=null){

                    mp.pause();
                    // Changing button image to play button
                    btnPlay.setImageResource(R.drawable.btn_play);
                }
            }else{
                // Resume song
                if(mp!=null){
                    mp.start();
                    // Changing button image to pause button
                    btnPlay.setImageResource(R.drawable.btn_pause);
                }
            }

        }
    });



}



/**
 * Function to play a song
 * @param songIndex - index of song
 * */
public void  playSong(int songIndex){
    // Play song
    try {
        mp.reset();
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {

            mp.setDataSource("http://test.com/test/upload/Twale_FLO.mp3");
            mp.prepareAsync();
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {                        
                    mp.start();
                    totalDuration =mp.getDuration();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }




        // set Progress bar values
        songProgressBar.setProgress(0);
        songProgressBar.setMax(99);

        // Updating progress bar
        updateProgressBar();


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

/**
 * Update timer on seekbar
 * */
public void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask, 100);
}

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        long currentDuration = mp.getCurrentPosition();
        long totalDuration = mp.getDuration();

        // Displaying Total Duration time
       songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));

        // Displaying time completed playing
        songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

        // Updating progress bar
        int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration ));
        Log.d("Progress", "" + progress);
        songProgressBar.setProgress(progress);

        // Running this thread after 100 milliseconds
        mHandler.postDelayed(this, 100);
    }
};

/**
 *
 * */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

}

/**
 * When user starts moving the progress handler
 * */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // remove message Handler from updating progress bar
    mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
 * When user stops moving the progress hanlder
 * */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    // forward or backward to certain seconds
    mp.seekTo(currentPosition);

    // update timer progress again
    updateProgressBar();
}

/**
 * On Song Playing completed
 * if repeat is ON play same song again
 * if shuffle is ON play random song
 * */
@Override
public void onCompletion(MediaPlayer arg0) {

    // check for repeat is ON or OFF
    if(isRepeat){
        // repeat is on play same song again
        playSong(currentSongIndex);
    }  else{
            // play first song
            playSong(0);
            currentSongIndex = 0;
    }
}

@Override
public void onDestroy(){
    super.onDestroy();
    mp.release();
}}

Please how can I get the total duration of the audio file streaming from online via android? Thanks in advance.

There are some problem with this topic.

  1. The getDuration() does not work on all API versions. So, it is not sure when it will work and when not.
  2. The other way around is to extract metadata. Unfortunately, android MediaMetadataRetriever doesn't work with online source. It works only with sd card files.

Fortunately there is a library available that can help us. And i got the duration with that library. So, these are steps.

  1. add compile 'com.github.wseemann:FFmpegMediaMetadataRetriever:1.0.3' to your gradle.build in dependency

Then you can get duration by below code

FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
            mmr.setDataSource("http://owatechinnovations.com/test/upload/Twale_FLO.mp3");
            mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM);
            mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST);
            long duration =Long.parseLong(mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION));
            duration=duration/1000;
            long minute=duration/(60);
            long second=duration-(minute*60);
            mmr.release();
            your_text_view.setText(minute+":"+second);

I get the result "4:18" 4 mins 18 secs. hope it helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM