Android带播放进度条的音乐播放器

前言: 使用MediaPlayer实现Android的音乐播放器,能够播放、暂停、停止歌曲;同时使用SeekBar来控制音乐的播放进度,可以通过调节SeekBar的进度来控制播放进度。

效果图如下:

1. 第一步

布局文件activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_margin="20dp"    android:layout_width="match_parent"    android:layout_height="match_parent">    <LinearLayout        android:orientation="vertical"        android:layout_marginTop="20dp"        android:layout_width="match_parent"        android:layout_height="wrap_content">        <TextView            android:id="@+id/music_name"            android:layout_gravity="center_horizontal"            android:layout_width="wrap_content"            android:layout_height="wrap_content"/>        <RelativeLayout            android:layout_width="match_parent"            android:layout_height="wrap_content">            <SeekBar                android:id="@+id/seekBar"                android:layout_marginTop="80dp"                android:layout_width="match_parent"                android:layout_height="wrap_content"/>            <LinearLayout                android:layout_below="@id/seekBar"                android:layout_alignEnd="@id/seekBar"                android:layout_width="wrap_content"                android:layout_height="wrap_content">                <TextView                    android:id="@+id/music_cur"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"/>                <TextView                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:text="/"/>                <TextView                    android:id="@+id/music_length"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"/>            LinearLayout>        RelativeLayout>    LinearLayout>   <LinearLayout       android:gravity="center"       android:layout_width="match_parent"       android:layout_height="match_parent">       <ImageButton           android:id="@+id/play"           android:src="@mipmap/bofang"           android:background="@null"           android:layout_width="wrap_content"           android:layout_height="wrap_content"/>       <ImageButton           android:id="@+id/pause"           android:src="@mipmap/pause"           android:background="@null"           android:layout_marginLeft="20dp"           android:layout_width="wrap_content"           android:layout_height="wrap_content"/>       <ImageButton           android:id="@+id/stop"           android:src="@mipmap/stop"           android:background="@null"           android:layout_marginLeft="20dp"           android:layout_width="wrap_content"           android:layout_height="wrap_content"/>   LinearLayout>    <LinearLayout        android:gravity="bottom|right"        android:orientation="vertical"        android:layout_width="match_parent"        android:layout_height="match_parent">        <ImageButton            android:id="@+id/volume_plus"            android:src="@mipmap/volume_increase"            android:background="@null"            android:layout_width="wrap_content"            android:layout_height="wrap_content"/>        <ImageButton            android:id="@+id/volume_decrease"            android:src="@mipmap/volume_decrease"            android:background="@null"            android:layout_marginTop="20dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"/>    LinearLayout>RelativeLayout>

2. 第二步

Activity——MusicActivity

public class MusicActivity extends AppCompatActivity implements View.OnClickListener {    private ImageButton play,pause,stop,volume_plus,volume_decrease;    private TextView musicName,musicLength,musicCur;    private SeekBar seekBar;    private MediaPlayer mediaPlayer = new MediaPlayer();    private AudioManager audioManager;    private Timer timer;    int maxVolume,currentVolume;    private boolean isSeekBarChanging;//互斥变量,防止进度条与定时器冲突。    private int currentPosition;//当前音乐播放的进度    SimpleDateFormat format;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_music);        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);        format = new SimpleDateFormat("mm:ss");        play = (ImageButton) findViewById(R.id.play);        pause = (ImageButton) findViewById(R.id.pause);        stop = (ImageButton) findViewById(R.id.stop);        volume_plus = (ImageButton) findViewById(R.id.volume_plus);        volume_decrease = (ImageButton) findViewById(R.id.volume_decrease);        musicName = (TextView) findViewById(R.id.music_name);        musicLength = (TextView) findViewById(R.id.music_length);        musicCur = (TextView) findViewById(R.id.music_cur);        seekBar = (SeekBar) findViewById(R.id.seekBar);        seekBar.setOnSeekBarChangeListener(new MySeekBar());        play.setOnClickListener(MusicActivity.this);        pause.setOnClickListener(MusicActivity.this);        stop.setOnClickListener(MusicActivity.this);        volume_plus.setOnClickListener(MusicActivity.this);        volume_decrease.setOnClickListener(MusicActivity.this);        if (ContextCompat.checkSelfPermission(MusicActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=                PackageManager.PERMISSION_GRANTED) {            ActivityCompat.requestPermissions(MusicActivity.this,                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);        }else {            initMediaPlayer();//初始化mediaplayer        }    }    private void initMediaPlayer() {        try {            mediaPlayer.setDataSource("/sdcard/music.mp3");//指定音频文件的路径            mediaPlayer.prepare();//让mediaplayer进入准备状态            mediaPlayer.setLooping(true);            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {                public void onPrepared(MediaPlayer mp) {                    seekBar.setMax(mediaPlayer.getDuration());                    musicLength.setText(format.format(mediaPlayer.getDuration())+"");                    musicCur.setText("00:00");                    musicName.setText("music.mp3");                }            });        } catch (Exception e) {            e.printStackTrace();        }    }    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {        switch (requestCode) {            case 1:                if (grantResults.length > 0 &&                        grantResults[0] == PackageManager.PERMISSION_GRANTED) {                    initMediaPlayer();                } else {                    Toast.makeText(MusicActivity.this,"denied access",Toast.LENGTH_SHORT).show();                    finish();                }                break;            default:        }    }    @Override    public void onClick(View view) {        switch (view.getId()){            case R.id.play:                if (!mediaPlayer.isPlaying()) {                    mediaPlayer.start();//开始播放                    mediaPlayer.seekTo(currentPosition);                    //监听播放时回调函数                    timer = new Timer();                    timer.schedule(new TimerTask() {                        Runnable updateUI = new Runnable() {                            @Override                            public void run() {                                musicCur.setText(format.format(mediaPlayer.getCurrentPosition())+"");                            }                        };                        @Override                        public void run() {                            if(!isSeekBarChanging){                                seekBar.setProgress(mediaPlayer.getCurrentPosition());                                runOnUiThread(updateUI);                            }                        }                    },0,50);                }                break;            case R.id.pause:                if (mediaPlayer.isPlaying()) {                    mediaPlayer.pause();//暂停播放                }                break;            case R.id.stop:                Toast.makeText(MusicActivity.this,"停止播放",Toast.LENGTH_SHORT).show();                if (mediaPlayer.isPlaying()) {                    mediaPlayer.reset();//停止播放                    initMediaPlayer();                }                break;            //音量加            case R.id.volume_plus:                maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,AudioManager.FLAG_SHOW_UI);                currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);                Toast.makeText(MusicActivity.this,"音量增加,最大音量是:" + maxVolume + ",当前音量" + currentVolume,                        Toast.LENGTH_SHORT).show();                break;            //音量减            case R.id.volume_decrease:                maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,AudioManager.FLAG_SHOW_UI);                currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);                Toast.makeText(MusicActivity.this,"音量减小,最大音量是:" + maxVolume + ",当前音量" + currentVolume,                        Toast.LENGTH_SHORT).show();                break;            default:                break;        }    }    @Override    protected void onDestroy() {        super.onDestroy();        isSeekBarChanging = true;        if (mediaPlayer != null) {            mediaPlayer.stop();            mediaPlayer.release();            mediaPlayer = null;        }        if (timer != null){            timer.cancel();            timer = null;        }    }    /*进度条处理*/    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {        public void onProgressChanged(SeekBar seekBar, int progress,                                      boolean fromUser) {        }        /*滚动时,应当暂停后台定时器*/        public void onStartTrackingTouch(SeekBar seekBar) {            isSeekBarChanging = true;        }        /*滑动结束后,重新设置值*/        public void onStopTrackingTouch(SeekBar seekBar) {            isSeekBarChanging = false;            mediaPlayer.seekTo(seekBar.getProgress());        }    }

总结: 就这样我们就使用MediaPlayer实现了简单的音乐播放器,能够播放、暂停、停止歌曲;同时使用SeekBar来控制音乐的播放进度,通过调节SeekBar的进度我们就可以实现播放进度的控制。

更多相关文章

  1. 使用ProgressBar显示进度条
  2. Android(安卓)五子棋开发经验
  3. 2011.07.18(4)——— android 播放gif
  4. APP开发实战85-帧动画
  5. Android使用FFmpeg(六)--ffmpeg实现音视频同步播放
  6. Android(安卓)各种音量的获取和设置
  7. 2011.07.18(4)——— android 播放gif
  8. Android简单自定义圆形和水平ProgressBar
  9. Android(安卓)系统音量最大值的定义位置以及默认值的修改方法

随机推荐

  1. speex算法在android上的移植
  2. 为菜鸟量身定制0基础android逆袭课程(颠覆
  3. 一分钟帮你提升Android(安卓)studio 编译
  4. 高效android编程
  5. 34、Android编写应用-从模板添加代码
  6. Android手机硬件信息的查看和软件安装方
  7. 自己实现的android树控件,android TreeVie
  8. Android(安卓)三种常用实现自定义圆形进
  9. [置顶] Android(安卓)动画:你真的会使用插
  10. unbuntu 14.04下NDK环境的搭建以及无法设