本地音乐播放器

音乐播放器

      • Activity
      • MusicUtils
      • Adapter

Activity

package com.example.musicplayer3;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.musicplayer3.adapter.MyAdapter;
import com.example.musicplayer3.entity.MusicBean;
import com.example.musicplayer3.entity.MusicUtils;

import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private ListView lv;
    private ImageView imageViewPic1;
    private TextView textViewName;
    private SeekBar seekBarId;
    private ImageButton imageViewList;
    private ImageButton imageViewPrev;
    private ImageButton imageViewPlay;
    private ImageButton imageViewNext;
    private TextView textViewXunhuan;
    private TextView textViewSingle;
    private TextView textViewRandom;


    private MyAdapter adapter;//适配器
    private MediaPlayer mediaPlayer;//音乐播放器
    private List<MusicBean> list;//数据源
    private Timer timer;//计时器
    private boolean isplay = false;//是否播放
    private int index = 0;//当前播放歌曲下标
    private int model = MusicUtils.ORDER;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 101);
        } else {
            initView();
        }

    }

    private void initView() {
        lv = (ListView) findViewById(R.id.lv);
        imageViewPic1 = (ImageView) findViewById(R.id.imageView_pic_1);
        textViewName = (TextView) findViewById(R.id.textView_name);
        seekBarId = (SeekBar) findViewById(R.id.seekBar_id);
        imageViewList = (ImageButton) findViewById(R.id.imageView_list);
        imageViewPrev = (ImageButton) findViewById(R.id.imageView_prev);
        imageViewPlay = (ImageButton) findViewById(R.id.imageView_play);
        imageViewNext = (ImageButton) findViewById(R.id.imageView_next);

        list = MusicUtils.queryMusic(this);
        adapter = new MyAdapter(this, list);
        lv.setAdapter(adapter);

        mediaPlayer = new MediaPlayer();

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {//listView条目点击
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                isplay = true;
                imageViewPlay.setBackgroundResource(R.drawable.playbar_btn_pause);
                textViewName.setText(list.get(position).getTitle());

                seekBarId.setMax(Integer.parseInt(list.get(position).getDuration()));
                player(position);
            }
        });

        seekBarId.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {//拖动进度条进度
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mediaPlayer.seekTo(progress);
                    isplay = true;
                    mediaPlayer.start();
                    imageViewPlay.setBackgroundResource(R.drawable.playbar_btn_pause);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        imageViewPlay.setOnClickListener(new View.OnClickListener() {//播放暂停
            @Override
            public void onClick(View v) {
                if (isplay) {
                    isplay = false;
                    mediaPlayer.pause();
                    imageViewPlay.setBackgroundResource(R.drawable.playbar_btn_play);
                } else {
                    isplay = true;
                    mediaPlayer.start();
                    imageViewPlay.setBackgroundResource(R.drawable.playbar_btn_pause);
                }
            }
        });

        imageViewPrev.setOnClickListener(new View.OnClickListener() {//上一首
            @Override
            public void onClick(View v) {
                index--;
                if (index < 0) {
                    index = list.size() - 1;
                }
                player(index);
                textViewName.setText(list.get(index).getTitle());
                imageViewPlay.setBackgroundResource(R.drawable.playbar_btn_pause);
            }
        });

        imageViewNext.setOnClickListener(new View.OnClickListener() {//下一曲
            @Override
            public void onClick(View v) {
                switch (model) {
                    case MusicUtils.ORDER:
                        next(index++);
                        break;
                    case MusicUtils.RANDOM:
                        index = new Random().nextInt(list.size());
                        next(index);
                        break;
                    case MusicUtils.SINGLE:
                        next(++index);
                        break;
                }
            }
        });

        imageViewList.setOnClickListener(new View.OnClickListener() {//播放模式
            @Override
            public void onClick(View v) {
                PopupWindow popupWindow = new PopupWindow();
                View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_layout, null);

                textViewXunhuan = (TextView) inflate.findViewById(R.id.textView_xunhuan);
                textViewXunhuan.setOnClickListener(new View.OnClickListener() {//顺序播放
                    @Override
                    public void onClick(View v) {
                        model = MusicUtils.ORDER;
                        Toast.makeText(MainActivity.this, "循环播放", Toast.LENGTH_SHORT).show();
                    }
                });

                textViewSingle = (TextView) inflate.findViewById(R.id.textView_single);
                textViewSingle.setOnClickListener(new View.OnClickListener() {//单曲循环
                    @Override
                    public void onClick(View v) {
                        model = MusicUtils.SINGLE;
                        Toast.makeText(MainActivity.this, "单曲循环", Toast.LENGTH_SHORT).show();
                    }
                });

                textViewRandom = (TextView) inflate.findViewById(R.id.textView_random);
                textViewRandom.setOnClickListener(new View.OnClickListener() {//随机播放
                    @Override
                    public void onClick(View v) {
                        model = MusicUtils.RANDOM;
                        Toast.makeText(MainActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
                    }
                });

                popupWindow.setContentView(inflate);
                popupWindow.setWidth(200);
                popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setOutsideTouchable(true);
                popupWindow.showAsDropDown(textViewName, 0, -200);
            }
        });
    }

    private void next(int index) {

        if (index > list.size() - 1) {
            index = 0;
        }
        isplay = true;
        imageViewPlay.setBackgroundResource(R.drawable.playbar_btn_pause);
        textViewName.setText(list.get(index).getTitle());
        player(index);
    }

    private void player(int position) {

        if (timer != null){
            timer.cancel();
        }

        isplay = true;

        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(list.get(position).getData());
            mediaPlayer.prepareAsync();

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    switch (model) {
                        case MusicUtils.ORDER:
                            next(index++);
                            break;
                        case MusicUtils.RANDOM:
                            index = new Random().nextInt(list.size());
                            next(index);
                            break;
                        case MusicUtils.SINGLE:
                            next(index);
                            break;
                    }
                }
            });

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    return false;
                }
            });

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        timer = new Timer();
        timer.schedule(new TimerTask() {//计时器刷新进度条进度
            @Override
            public void run() {
                seekBarId.setProgress(mediaPlayer.getCurrentPosition());
            }
        }, 0, 1000);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 101 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initView();
        } else {
            finish();
        }
    }
}

MusicUtils

package com.example.musicplayer3.entity;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MusicUtils {

    public static final int ORDER = 0;
    public static final int RANDOM = 1;
    public static final int SINGLE = 2;

    public static List<MusicBean> queryMusic(Context context){
        List<MusicBean> list = new ArrayList<>();
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        if (cursor != null){
            while (cursor.moveToNext()){
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String size = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
                if (Integer.parseInt(size) >= 1024*80){
                    MusicBean musicBean = new MusicBean(title, artist, duration, size, data);
                    list.add(musicBean);
                }
            }
        }
        cursor.close();
        return list;
    }

}

Adapter

package com.example.musicplayer3.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.musicplayer3.R;
import com.example.musicplayer3.entity.MusicBean;

import java.util.List;

public class MyAdapter extends BaseAdapter {

    private Context context;
    private List<MusicBean> list;
    private LayoutInflater layoutInflater;

    public MyAdapter(Context context, List<MusicBean> list) {
        this.context = context;
        this.list = list;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null){
            viewHolder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.list_layout,null);
            viewHolder.imageViewPic = convertView.findViewById(R.id.imageView_pic);
            viewHolder.textViewTitle = convertView.findViewById(R.id.textView_title);
            viewHolder.textViewArtist = convertView.findViewById(R.id.textView_artist);
            viewHolder.textViewDuration = convertView.findViewById(R.id.textView_duration);
            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.imageViewPic.setBackgroundResource(R.mipmap.ic_launcher);
        viewHolder.textViewTitle.setText(list.get(position).getTitle());
        viewHolder.textViewArtist.setText(list.get(position).getArtist());
        String duration = list.get(position).getDuration();
        String time = Integer.parseInt(duration) / 1000 / 60 + ":" + Integer.parseInt(duration) / 1000 % 60;
        viewHolder.textViewDuration.setText(time);
        return convertView;
    }

    public static class ViewHolder{
        private ImageView imageViewPic;
        private TextView textViewTitle;
        private TextView textViewDuration;
        private TextView textViewArtist;
    }
}

你可能感兴趣的:(本地音乐播放器)