带进度条的android studio音乐播放器代码
时间: 2023-09-18 14:14:42 浏览: 240
带进度条的音乐播放器
5星 · 资源好评率100%
以下是一个简单的带进度条的 Android 音乐播放器代码示例:
1. 首先,你需要在你的布局文件中添加一个 SeekBar 组件用于显示音乐播放进度:
```xml
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp" />
```
2. 接下来,在你的 Activity 或 Fragment 中,你需要获取到 SeekBar 组件,并设置其最大值为音乐的总时长:
```java
SeekBar seekBar = findViewById(R.id.seekBar);
int musicDuration = mediaPlayer.getDuration(); // mediaPlayer 是你的音乐播放器对象
seekBar.setMax(musicDuration);
```
3. 然后,在你的音乐播放器对象中,你需要添加一个监听器来更新 SeekBar 的进度:
```java
mediaPlayer.setOnSeekBarChangeListener(new MediaPlayer.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mediaPlayer.seekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
```
4. 最后,在你的音乐播放器对象中,你需要在播放音乐时更新 SeekBar 的进度:
```java
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
int currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
handler.postDelayed(this, 1000); // 每隔1秒更新一次 SeekBar 的进度
}
};
handler.postDelayed(runnable, 0);
```
完整的代码示例:
```java
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SeekBar seekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = findViewById(R.id.seekBar);
mediaPlayer = MediaPlayer.create(this, R.raw.music);
mediaPlayer.setLooping(true);
mediaPlayer.seekTo(0);
int musicDuration = mediaPlayer.getDuration();
seekBar.setMax(musicDuration);
mediaPlayer.setOnSeekBarChangeListener(new MediaPlayer.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mediaPlayer.seekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
int currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 0);
Button playButton = findViewById(R.id.playButton);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.start();
}
});
Button pauseButton = findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.pause();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.release();
mediaPlayer = null;
}
}
```
阅读全文