如何显示使用媒体播放器播放的mp3文件的当前持续时间和总持续时间

时间:2018-12-29 20:22:05

标签: java android android-studio

如何在文本视图中显示当前播放时长和mp3文件的总时长。 请帮助我,我已经为此工作了好几天,任何帮助将不胜感激。预先感谢。

我的下面的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    seekBar = (SeekBar) findViewById(R.id.seekBar1);
    startMedia = (Button) findViewById(R.id.button1);
    stopMedia = (Button) findViewById(R.id.button2);
    startMedia.setOnClickListener(this);
    stopMedia.setOnClickListener(this);
    seekBar.setOnSeekBarChangeListener(this);
    seekBar.setEnabled(false);
}

public void run() {
    int currentPosition = mp.getCurrentPosition();
    int total = mp.getDuration();

    while (mp != null && currentPosition < total) {
        try {
            Thread.sleep(1000);
            currentPosition = mp.getCurrentPosition();
        } catch (InterruptedException e) {
            return;
        } catch (Exception e) {
            return;
        }
        seekBar.setProgress(currentPosition);
    }
}

public void onClick(View v) {
    if (v.equals(startMedia)) {
        if (mp == null) {
            mp = MediaPlayer.create(getApplicationContext(), Uri.parse("https://eplayer.000webhostapp.com/Sleep Away.mp3"));
            seekBar.setEnabled(true);
        }
        if (mp.isPlaying()) {
            mp.pause();
            startMedia.setText("play");
        } else {
            mp.start();
            startMedia.setText("pause");
            seekBar.setMax(mp.getDuration());
            new Thread(this).start();
        }
    }

    if (v.equals(stopMedia) && mp != null) {
        if (mp.isPlaying() || mp.getDuration() > 0) {
            mp.stop();
            mp = null;
            startMedia.setText("play");
            seekBar.setProgress(0);
        }
    }

}

public void onProgressChanged(SeekBar seekBar, int progress,
                              boolean fromUser) {
    try {
        if (mp.isPlaying() || mp != null) {
            if (fromUser)
                mp.seekTo(progress);
        } else if (mp == null) {
            Toast.makeText(getApplicationContext(), "Media is not running",
                    Toast.LENGTH_SHORT).show();
            seekBar.setProgress(0);
        }
    } catch (Exception e) {
        Log.e("seek bar", "" + e);
        seekBar.setEnabled(false);

    }
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub

}

0 个答案:

没有答案