1.布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="horizontal"> <ImageButton android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/main_ib"/> <SeekBar android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="4" android:id="@+id/main_sb"/> </LinearLayout>
2.mainactivity.java
import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageButton; import android.widget.SeekBar; public class MainActivity extends AppCompatActivity { private SeekBar main_sb; private ImageButton main_ib; private MediaPlayer mediaplayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取控件id main_sb = findViewById(R.id.main_sb); main_ib = findViewById(R.id.main_ib); //设置按钮初始图标 main_ib.setImageResource(android.R.drawable.ic_media_play); main_ib.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //判断 if (mediaplayer==null){ //放入歌曲 mediaplayer=MediaPlayer.create(MainActivity.this,R.raw.d); //设置进度条最大长度为音频时长 main_sb.setMax(mediaplayer.getDuration()); //开始播放 mediaplayer.start(); //使按钮变为暂停图标 main_ib.setImageResource(android.R.drawable.ic_media_pause); //线程开始运行 new myThread().start(); }else if (mediaplayer.isPlaying()){ //如果正在播放 (暂停) mediaplayer.pause(); //改变按钮为播放 main_ib.setImageResource(android.R.drawable.ic_media_play); //不用添加图片 }else{ //如果没有播放 (播放) mediaplayer.start(); main_ib.setImageResource(android.R.drawable.ic_media_pause); } } }); //设置进度条快进效果 main_sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { //值改变 @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } //值改变前 @Override public void onStartTrackingTouch(SeekBar seekBar) { } //值改变后 @Override public void onStopTrackingTouch(SeekBar seekBar) { mediaplayer.seekTo(main_sb.getProgress()); } }); } //设置一个线程运行进度条 class myThread extends Thread{ @Override public void run() { super.run(); //判断当前播放位置是否小于总时长 while (main_sb.getProgress()<=main_sb.getMax()) { //设置进度条当前位置为音频播放位置 main_sb.setProgress(mediaplayer.getCurrentPosition()); } } } }