Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

url - Android mediaPlayer.getDuration() return 0 or -1

I am creating online media player where we are playing song with the help of URL. In Media Player we are displaying Total time of song, for displaying time we are using mediaPlayer.getDuration() function but it always returning -1.

When I am passing Drop Box URL then it working but when I pass my server URL (https://) then it not working.

2021-01-25 14:50:33.777 11438-11438/com.dd.xyz W/MediaPlayer: Use of stream types is deprecated for operations other than volume control
2021-01-25 14:50:33.777 11438-11438/com.dd.xyz W/MediaPlayer: See the documentation of setAudioStreamType() for what to use instead with android.media.AudioAttributes to qualify your playback use case
2021-01-25 14:50:33.778 11438-11438/com.dd.xyz V/MediaHTTPService: MediaHTTPService(android.media.MediaHTTPService@6a1c34b): Cookies: null
2021-01-25 14:50:33.783 11438-11663/com.dd.xyz V/MediaHTTPService: makeHTTPConnection: CookieHandler (java.net.CookieManager@ea97e0b) exists.
2021-01-25 14:50:33.783 11438-11663/com.dd.xyz V/MediaHTTPService: makeHTTPConnection(android.media.MediaHTTPService@6a1c34b): cookieHandler: java.net.CookieManager@ea97e0b Cookies: null
2021-01-25 14:50:34.616 11438-11438/com.dd.xyz I/mediaFileLength: -1

Below is code -

public class MainActivity extends AppCompatActivity {

    private ImageView imageViewPlayPause;
    private TextView textCurrenTime,textTotalDuration;
    private SeekBar playerSeekBar;
    private MediaPlayer mediaPlayer;
    private Handler handler =new Handler();
    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageViewPlayPause=findViewById(R.id.imagePlayPause);
        textCurrenTime=findViewById(R.id.textCurrentTime);
        textTotalDuration=findViewById(R.id.textTotalDuration);
        playerSeekBar=findViewById(R.id.playerSeekBar);

        mediaPlayer=new MediaPlayer();
        playerSeekBar.setMax(100);

        imageViewPlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mediaPlayer.isPlaying()){
                    handler.removeCallbacks(updater);
                    mediaPlayer.pause();
                    imageViewPlayPause.setImageResource(R.drawable.ic_play);
                }
                else{
                    mediaPlayer.start();
                    imageViewPlayPause.setImageResource(R.drawable.ic_pause);
                    updateSeekBar();
                }
            }
        });
        prepareMediaPlayer();
        playerSeekBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                SeekBar seekBar=(SeekBar) view;
                int playPosition=(mediaPlayer.getDuration()/100)*seekBar.getProgress();
                mediaPlayer.seekTo(playPosition);
                textCurrenTime.setText(milliSecondsToTimer(mediaPlayer.getCurrentPosition()));
                return false;
            }
        });
    }

    private void prepareMediaPlayer(){
        try{
            mediaPlayer.setDataSource("https://varkarisanskruti.com/sample.mp3");
            mediaPlayer.prepare();
            textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
            Log.d("musicPlayerTimehere", String.valueOf(mediaPlayer.getDuration()));
        }
        catch(Exception e)
        {
            Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }

    private Runnable updater=new Runnable() {
        @Override
        public void run() {
            updateSeekBar();
            long currentDuration=mediaPlayer.getCurrentPosition();
            textCurrenTime.setText(milliSecondsToTimer(currentDuration));
        }
    };


    private void updateSeekBar(){
        if(mediaPlayer.isPlaying()){
            playerSeekBar.setProgress((int)(((float) mediaPlayer.getCurrentPosition()/mediaPlayer.getDuration())*100));
            handler.postDelayed(updater,1000);
        }
    }



    private String milliSecondsToTimer(long milliSeconds){
        String timerString="";
        String secondString;
        int hour=(int) (milliSeconds/(1000*60*60));
        int minutes=(int)(milliSeconds%(1000*60*60))/(1000*60);
        int seconds=(int)((milliSeconds%(1000*60*60))%(1000*60)/1000);
        if(hour>0){
            timerString=hour+":";
        }
        if(seconds<10){
            secondString="0"+seconds;
        }
        else {
            secondString=""+seconds;
        }
        timerString=timerString+minutes+":"+secondString;
        return timerString;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

I tried this but this is for Zero and I can't use third party lib due to privacy/company policies.

Please Help...

Thank you in advance for helping...!

question from:https://stackoverflow.com/questions/65881968/android-mediaplayer-getduration-return-0-or-1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I tried multiple answers from stackoverflow, below are some for your reference but nothing is working -

How to get mp3 file duration Http streamed over Android MediaPlayer

mediaPlayer.getDuration() returns 0 after setDataSource and crashes app

MediaPlayer getDuration returns -1412558917

So I analyzed .mp3 file properties and found that if Bit Rate is 128kbps then mediaPlayer.getDuration() always returns 0 or -1.

I know you might don't believe that's why I recorded the video and uploaded it on Youtube. Here is link for your reference. https://youtu.be/-AKw59eb6nM

For me converting mp3 file to 320kbps from 128kbps is the solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...