帮我随便写一个Androidstudio音乐播放界面代码
时间: 2024-04-30 22:24:19 浏览: 112
好的,以下是一个简单的 Android Studio 音乐播放界面的代码示例:
```
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private Button playButton;
private SeekBar seekBar;
private TextView currentTimeTextView, totalTimeTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化界面元素
playButton = findViewById(R.id.play_button);
seekBar = findViewById(R.id.seek_bar);
currentTimeTextView = findViewById(R.id.current_time_text_view);
totalTimeTextView = findViewById(R.id.total_time_text_view);
// 创建 MediaPlayer 对象
mediaPlayer = MediaPlayer.create(this, R.raw.music_file);
// 设置播放按钮的点击事件
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
playButton.setText("播放");
} else {
mediaPlayer.start();
playButton.setText("暂停");
}
}
});
// 设置 SeekBar 的拖动事件
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mediaPlayer.seekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// do nothing
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// do nothing
}
});
// 设置 MediaPlayer 的播放完成事件
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
playButton.setText("播放");
seekBar.setProgress(0);
}
});
// 更新播放进度和时间显示
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (mediaPlayer != null) {
final int currentPosition = mediaPlayer.getCurrentPosition();
final int totalDuration = mediaPlayer.getDuration();
// 更新 SeekBar 和时间显示
runOnUiThread(new Runnable() {
@Override
public void run() {
seekBar.setMax(totalDuration);
seekBar.setProgress(currentPosition);
currentTimeTextView.setText(formatTime(currentPosition));
totalTimeTextView.setText(formatTime(totalDuration));
}
});
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
// 格式化时间显示
private String formatTime(int time) {
int seconds = time / 1000;
int minutes = seconds / 60;
seconds %= 60;
return String.format("%02d:%02d", minutes, seconds);
}
// 释放 MediaPlayer 资源
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
```
注意:这只是一个简单的示例代码,仅供参考。实际上,一个完整的音乐播放器可能需要更多的功能和优化。
阅读全文