I have a simple player and recorder. Everything works great but have a one problem. I want to add seek bar to see progress in playing record and use this seek bar to set place from player should play. I have onProgress but with no effect. This is code:
我有一个简单的播放器和录音机。一切都很好,但有一个问题。我想添加搜索栏以查看播放记录的进度,并使用此搜索栏来设置播放器应该播放的位置。我有onProgress但没有效果。这是代码:
package com.example.recorder;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity implements OnSeekBarChangeListener
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private SeekBar seekBar;
private MediaRecorder mRecorder = null;
private Button startRecord, startPlaying, stopPlaying;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void startPlaying() {
if(mPlayer != null && mPlayer.isPlaying()){
mPlayer.pause();
} else if(mPlayer != null){
mPlayer.start();
}else{
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
startPlaying.setText("Start playing");
}
private void pausePlaying(){
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
startPlaying = (Button) findViewById(R.id.buttonStartPlay);
stopPlaying = (Button) findViewById(R.id.buttonStopPlaying);
startRecord = (Button) findViewById(R.id.buttonStartRecord);
seekBar = (SeekBar) findViewById(R.id.seekBar);
startRecord.setOnClickListener(new OnClickListener() {
boolean mStartRecording = true;
@Override
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
startRecord.setText("Stop recording");
} else {
startRecord.setText("Start recording");
}
mStartRecording = !mStartRecording;
}
});
startPlaying.setOnClickListener(new OnClickListener() {
boolean mStartPlaying = true;
@Override
public void onClick(View v) {
//onPlay(mStartPlaying);
startPlaying();
if (mStartPlaying) {
startPlaying.setText("Stop playing");
} else {
startPlaying.setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
});
stopPlaying.setOnClickListener(new OnClickListener() {
boolean mStartPlaying = true;
@Override
public void onClick(View v) {
stopPlaying();
}
});
}
@Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser){
mPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
else{
// the event was fired from code and you shouldn't call player.seekTo()
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Any ideas how use seek bar to see progress and set place from record should play?
如何使用搜索栏来查看进度和从记录中设置位置的任何想法应该发挥?
11 个解决方案
#1
111
To create a 'connection' between SeekBar
and MediaPlayer
you need first to get your current recording max duration and set it to your seek bar.
要在SeekBar和MediaPlayer之间创建“连接”,首先需要获取当前录制的最长持续时间并将其设置为搜索栏。
mSeekBar.setMax(mFileDuration); // where mFileDuration is mMediaPlayer.getDuration();
After you initialise your MediaPlayer
and for example press play button, you should create handler and post runnable so you can update your SeekBar
(in the UI thread
itself) with the current position of your MediaPlayer
like this :
初始化MediaPlayer后,例如按下播放按钮,您应该创建处理程序并发布runnable,这样您就可以使用MediaPlayer的当前位置更新SeekBar(在UI线程本身中),如下所示:
private Handler mHandler = new Handler();
//Make sure you update Seekbar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if(mMediaPlayer != null){
int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
mSeekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
and update that value every second.
并每秒更新该值。
If you need to update the MediaPlayer
's position while user drag your SeekBar
you should add OnSeekBarChangeListener
to your SeekBar
and do it there :
如果您需要在用户拖动SeekBar时更新MediaPlayer的位置,您应该将OnSeekBarChangeListener添加到SeekBar并在那里执行:
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mMediaPlayer != null && fromUser){
mMediaPlayer.seekTo(progress * 1000);
}
}
});
And that should do the trick! : )
那应该是诀窍! :)
EDIT: One thing which I've noticed in your code, don't do :
编辑:我在你的代码中注意到的一件事,不要做:
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
make all initialisations in your onCreate();
, do not create constructors of your Activity
.
在你的onCreate()中进行所有初始化; ,不要创建Activity的构造函数。
#2
7
I've used this tutorial with success, it's really simple to understand: www.androidhive.info/2012/03/android-building-audio-player-tutorial/
我已成功使用本教程,理解起来非常简单:www.androidhive.info/2012/03/android-building-audio-player-tutorial/
This is the interesting part:
这是有趣的部分:
/**
* Update timer on seekbar
* */
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// 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();
}
#3
2
After you initialize your MediaPlayer
and SeekBar
, you can do this :
初始化MediaPlayer和SeekBar后,您可以执行以下操作:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
}
},0,1000);
This updates SeekBar
every second(1000ms)
这会每秒更新SeekBar(1000ms)
And for updating MediaPlayer
, if user drag SeekBar
, you must add OnSeekBarChangeListener
to your SeekBar
:
要更新MediaPlayer,如果用户拖动SeekBar,则必须将OnSeekBarChangeListener添加到SeekBar:
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
mMediaPlayer.seekTo(i);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
HAPPY CODING!!!
快乐的编码!!!
#4
1
check this, you should give arguments in msecs, Dont just send progress
to seekTo(int)
检查一下,你应该在msecs中给出参数,不要只是将进度发送到seekTo(int)
and also check this getCurrentPostion() and getDuration().
并检查此getCurrentPostion()和getDuration()。
You can do some calcuations, ie., convert progress
in msec like msce = (progress/100)*getDuration()
then do seekTo(msec)
你可以做一些计算,即,以毫秒为单位转换进度,如msce =(progress / 100)* getDuration()然后执行seekTo(msec)
Or else i have an easy idea, you don't need to change any code anywer else just add seekBar.setMax(mPlayer.getDuration())
once your media player is prepared.
或者我有一个简单的想法,你不需要更改任何其他代码只需添加seekBar.setMax(mPlayer.getDuration())一旦你的媒体播放器准备好。
and here is link exactly what you want seek bar update
这里链接正是你想要的条形更新
#5
1
int pos = 0;
yourSeekBar.setMax(mPlayer.getDuration());
After You start Your MediaPlayer
i.e mplayer.start()
启动MediaPlayer后,即mplayer.start()
Try this code
while(mPlayer!=null){
try {
Thread.sleep(1000);
pos = mPlayer.getCurrentPosition();
} catch (Exception e) {
//show exception in LogCat
}
yourSeekBar.setProgress(pos);
}
Before you added this code you have to create xml
resource for SeekBar
and use it in Your Activity
class of ur onCreate()
method.
在添加此代码之前,您必须为SeekBar创建xml资源,并在您的Activity onCreate()方法的类中使用它。
#6
0
To add on to @hardartcore's answer.
添加到@ hardartcore的答案。
-
Instead of calling postDelayed on a Handler, the best approach would be to get callbacks from the
MediaPlayer
during play-back and then accordingly update the seekBar with the progress.而不是在Handler上调用postDelayed,最好的方法是在播放期间从MediaPlayer获取回调,然后根据进度更新seekBar。
-
Also, pause your
MediaPlayer
atonStartTrackingTouch(SeekBar seekBar)
of theOnSeekBarChangeListener
and then re-start it ononStopTrackingTouch(SeekBar seekBar)
.此外,在OnSeekBarChangeListener的onStartTrackingTouch(SeekBar seekBar)暂停MediaPlayer,然后在onStopTrackingTouch(SeekBar seekBar)上重新启动它。
#7
0
Based on previous statements, for better performance, you can also add an if condition
根据以前的陈述,为了获得更好的性能,您还可以添加if条件
if (player.isPlaying() {
handler.postDelayed(..., 1000);
}
#8
0
The below code worked for me.
以下代码对我有用。
I've created a method for seekbar
我为seekbar创建了一个方法
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
getDurationTimer();
getSeekBarStatus();
}
//Creating duration time method
public void getDurationTimer(){
final long minutes=(mSongDuration/1000)/60;
final int seconds= (int) ((mSongDuration/1000)%60);
SongMaxLength.setText(minutes+ ":"+seconds);
}
//creating a method for seekBar progress
public void getSeekBarStatus(){
new Thread(new Runnable() {
@Override
public void run() {
// mp is your MediaPlayer
// progress is your ProgressBar
int currentPosition = 0;
int total = mp.getDuration();
seekBar.setMax(total);
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
}).start();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress=0;
@Override
public void onProgressChanged(final SeekBar seekBar, int ProgressValue, boolean fromUser) {
if (fromUser) {
mp.seekTo(ProgressValue);//if user drags the seekbar, it gets the position and updates in textView.
}
final long mMinutes=(ProgressValue/1000)/60;//converting into minutes
final int mSeconds=((ProgressValue/1000)%60);//converting into seconds
SongProgress.setText(mMinutes+":"+mSeconds);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
SongProgress and SongMaxLength are the TextView to show song duration and song length.
SongProgress和SongMaxLength是用于显示歌曲持续时间和歌曲长度的TextView。
#9
0
This works for me:
这对我有用:
seekbarPlayer.setMax(mp.getDuration());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(mp != null){
seekbarPlayer.setProgress(mp.getCurrentPosition());
}
mHandler.postDelayed(this, 1000);
}
});
#10
0
Try this Code:
试试这个代码:
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//You create MediaPlayer variable ==> set the path and start the audio.
mplayer = MediaPlayer.create(this, R.raw.example);
mplayer.start();
//Find the seek bar by Id (which you have to create in layout)
// Set seekBar max with length of audio
// You need a Timer variable to set progress with position of audio
final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setMax(mplayer.getDuration());
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
seekBar.setProgress(mplayer.getCurrentPosition());
}
}, 0, 1000);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Update the progress depending on seek bar
mplayer.seekTo(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#11
0
Code in Kotlin:
Kotlin的代码:
var updateSongTime = object : Runnable {
override fun run() {
val getCurrent = mediaPlayer?.currentPosition
startTimeText?.setText(String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long),
TimeUnit.MILLISECONDS.toSeconds(getCurrent?.toLong()) -
TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong()))))
seekBar?.setProgress(getCurrent?.toInt() as Int)
Handler().postDelayed(this, 1000)
}
}
For changing media player audio file every second
用于每秒更改媒体播放器音频文件
If user drags the seek bar then following code snippet can be use
如果用户拖动搜索栏,则可以使用以下代码段
Statified.seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
if(b && Statified.mediaPlayer != null){
Statified.mediaPlayer?.seekTo(i)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
#1
111
To create a 'connection' between SeekBar
and MediaPlayer
you need first to get your current recording max duration and set it to your seek bar.
要在SeekBar和MediaPlayer之间创建“连接”,首先需要获取当前录制的最长持续时间并将其设置为搜索栏。
mSeekBar.setMax(mFileDuration); // where mFileDuration is mMediaPlayer.getDuration();
After you initialise your MediaPlayer
and for example press play button, you should create handler and post runnable so you can update your SeekBar
(in the UI thread
itself) with the current position of your MediaPlayer
like this :
初始化MediaPlayer后,例如按下播放按钮,您应该创建处理程序并发布runnable,这样您就可以使用MediaPlayer的当前位置更新SeekBar(在UI线程本身中),如下所示:
private Handler mHandler = new Handler();
//Make sure you update Seekbar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if(mMediaPlayer != null){
int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
mSeekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
and update that value every second.
并每秒更新该值。
If you need to update the MediaPlayer
's position while user drag your SeekBar
you should add OnSeekBarChangeListener
to your SeekBar
and do it there :
如果您需要在用户拖动SeekBar时更新MediaPlayer的位置,您应该将OnSeekBarChangeListener添加到SeekBar并在那里执行:
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mMediaPlayer != null && fromUser){
mMediaPlayer.seekTo(progress * 1000);
}
}
});
And that should do the trick! : )
那应该是诀窍! :)
EDIT: One thing which I've noticed in your code, don't do :
编辑:我在你的代码中注意到的一件事,不要做:
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
make all initialisations in your onCreate();
, do not create constructors of your Activity
.
在你的onCreate()中进行所有初始化; ,不要创建Activity的构造函数。
#2
7
I've used this tutorial with success, it's really simple to understand: www.androidhive.info/2012/03/android-building-audio-player-tutorial/
我已成功使用本教程,理解起来非常简单:www.androidhive.info/2012/03/android-building-audio-player-tutorial/
This is the interesting part:
这是有趣的部分:
/**
* Update timer on seekbar
* */
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// 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();
}
#3
2
After you initialize your MediaPlayer
and SeekBar
, you can do this :
初始化MediaPlayer和SeekBar后,您可以执行以下操作:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
}
},0,1000);
This updates SeekBar
every second(1000ms)
这会每秒更新SeekBar(1000ms)
And for updating MediaPlayer
, if user drag SeekBar
, you must add OnSeekBarChangeListener
to your SeekBar
:
要更新MediaPlayer,如果用户拖动SeekBar,则必须将OnSeekBarChangeListener添加到SeekBar:
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
mMediaPlayer.seekTo(i);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
HAPPY CODING!!!
快乐的编码!!!
#4
1
check this, you should give arguments in msecs, Dont just send progress
to seekTo(int)
检查一下,你应该在msecs中给出参数,不要只是将进度发送到seekTo(int)
and also check this getCurrentPostion() and getDuration().
并检查此getCurrentPostion()和getDuration()。
You can do some calcuations, ie., convert progress
in msec like msce = (progress/100)*getDuration()
then do seekTo(msec)
你可以做一些计算,即,以毫秒为单位转换进度,如msce =(progress / 100)* getDuration()然后执行seekTo(msec)
Or else i have an easy idea, you don't need to change any code anywer else just add seekBar.setMax(mPlayer.getDuration())
once your media player is prepared.
或者我有一个简单的想法,你不需要更改任何其他代码只需添加seekBar.setMax(mPlayer.getDuration())一旦你的媒体播放器准备好。
and here is link exactly what you want seek bar update
这里链接正是你想要的条形更新
#5
1
int pos = 0;
yourSeekBar.setMax(mPlayer.getDuration());
After You start Your MediaPlayer
i.e mplayer.start()
启动MediaPlayer后,即mplayer.start()
Try this code
while(mPlayer!=null){
try {
Thread.sleep(1000);
pos = mPlayer.getCurrentPosition();
} catch (Exception e) {
//show exception in LogCat
}
yourSeekBar.setProgress(pos);
}
Before you added this code you have to create xml
resource for SeekBar
and use it in Your Activity
class of ur onCreate()
method.
在添加此代码之前,您必须为SeekBar创建xml资源,并在您的Activity onCreate()方法的类中使用它。
#6
0
To add on to @hardartcore's answer.
添加到@ hardartcore的答案。
-
Instead of calling postDelayed on a Handler, the best approach would be to get callbacks from the
MediaPlayer
during play-back and then accordingly update the seekBar with the progress.而不是在Handler上调用postDelayed,最好的方法是在播放期间从MediaPlayer获取回调,然后根据进度更新seekBar。
-
Also, pause your
MediaPlayer
atonStartTrackingTouch(SeekBar seekBar)
of theOnSeekBarChangeListener
and then re-start it ononStopTrackingTouch(SeekBar seekBar)
.此外,在OnSeekBarChangeListener的onStartTrackingTouch(SeekBar seekBar)暂停MediaPlayer,然后在onStopTrackingTouch(SeekBar seekBar)上重新启动它。
#7
0
Based on previous statements, for better performance, you can also add an if condition
根据以前的陈述,为了获得更好的性能,您还可以添加if条件
if (player.isPlaying() {
handler.postDelayed(..., 1000);
}
#8
0
The below code worked for me.
以下代码对我有用。
I've created a method for seekbar
我为seekbar创建了一个方法
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
getDurationTimer();
getSeekBarStatus();
}
//Creating duration time method
public void getDurationTimer(){
final long minutes=(mSongDuration/1000)/60;
final int seconds= (int) ((mSongDuration/1000)%60);
SongMaxLength.setText(minutes+ ":"+seconds);
}
//creating a method for seekBar progress
public void getSeekBarStatus(){
new Thread(new Runnable() {
@Override
public void run() {
// mp is your MediaPlayer
// progress is your ProgressBar
int currentPosition = 0;
int total = mp.getDuration();
seekBar.setMax(total);
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
}).start();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress=0;
@Override
public void onProgressChanged(final SeekBar seekBar, int ProgressValue, boolean fromUser) {
if (fromUser) {
mp.seekTo(ProgressValue);//if user drags the seekbar, it gets the position and updates in textView.
}
final long mMinutes=(ProgressValue/1000)/60;//converting into minutes
final int mSeconds=((ProgressValue/1000)%60);//converting into seconds
SongProgress.setText(mMinutes+":"+mSeconds);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
SongProgress and SongMaxLength are the TextView to show song duration and song length.
SongProgress和SongMaxLength是用于显示歌曲持续时间和歌曲长度的TextView。
#9
0
This works for me:
这对我有用:
seekbarPlayer.setMax(mp.getDuration());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(mp != null){
seekbarPlayer.setProgress(mp.getCurrentPosition());
}
mHandler.postDelayed(this, 1000);
}
});
#10
0
Try this Code:
试试这个代码:
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//You create MediaPlayer variable ==> set the path and start the audio.
mplayer = MediaPlayer.create(this, R.raw.example);
mplayer.start();
//Find the seek bar by Id (which you have to create in layout)
// Set seekBar max with length of audio
// You need a Timer variable to set progress with position of audio
final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setMax(mplayer.getDuration());
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
seekBar.setProgress(mplayer.getCurrentPosition());
}
}, 0, 1000);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Update the progress depending on seek bar
mplayer.seekTo(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#11
0
Code in Kotlin:
Kotlin的代码:
var updateSongTime = object : Runnable {
override fun run() {
val getCurrent = mediaPlayer?.currentPosition
startTimeText?.setText(String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long),
TimeUnit.MILLISECONDS.toSeconds(getCurrent?.toLong()) -
TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong()))))
seekBar?.setProgress(getCurrent?.toInt() as Int)
Handler().postDelayed(this, 1000)
}
}
For changing media player audio file every second
用于每秒更改媒体播放器音频文件
If user drags the seek bar then following code snippet can be use
如果用户拖动搜索栏,则可以使用以下代码段
Statified.seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
if(b && Statified.mediaPlayer != null){
Statified.mediaPlayer?.seekTo(i)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})