带进度条的音频播放
1.使用控件 自定义:SeekBar
2.更新进度条
xml代码
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="example.com.a201825.MainActivity"> <LinearLayout android:gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="vertical"> <SeekBar android:id="@+id/mSeekBar" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/mImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_record_pause" /> </LinearLayout> </RelativeLayout>
运行效果:
java代码
package example.com.a201825; import android.media.MediaPlayer; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.SeekBar; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private MediaPlayer mediaPlayer; private SeekBar seekBar; private ImageView imageView; private boolean flag = false; private Handler mHander = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: //1:判断MediaPlayer 不为空 if (mediaPlayer != null) { //总时间 int duration = mediaPlayer.getDuration(); //正在播放的时间 int currentPosition = mediaPlayer.getCurrentPosition(); seekBar.setProgress(currentPosition); } //2:更新进度条 break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //1.初始化音频播放器 mediaPlayer = new MediaPlayer(); seekBar = (SeekBar) findViewById(R.id.mSeekBar); imageView = (ImageView) findViewById(R.id.mImageView); //2.点击事件 imageView.setOnClickListener(MainActivity.this); //setDataSource //3:设置资源 //方式2 Uri.parse("")网址 R 存放音频 raw:二进制 //不用准备 mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.earth); //最大值 seekBar.setMax(mediaPlayer.getDuration()); } @Override public void onClick(View v) { //1.如果正在播放 暂停 //换图片 if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); flag = false; imageView.setImageResource(R.mipmap.ic_record_pause); } else { //暂停 播放 mediaPlayer.start(); flag = true; //播放的时候开一个线程 更新进度条 MusicThread musicThread = new MusicThread(); musicThread.start(); imageView.setImageResource(R.mipmap.ic_record_start); } } class MusicThread extends Thread { @Override public void run() { super.run(); //循环:不停的发送消息 更新进度条: 主线程 while (flag) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } mHander.sendEmptyMessage(1); } } } }