美文网首页
读取手机内存音乐,使用MediaPlayer播放

读取手机内存音乐,使用MediaPlayer播放

作者: Android初学者 | 来源:发表于2017-11-16 09:37 被阅读0次

    音乐工具类

    /**

    * 音乐工具类,

    */

    public class MusicUtils { public static ListgetMusicData(Context context) { Listlist = new ArrayList();

    // 媒体库查询语句(写一个工具类MusicUtils)

    Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,

    null, MediaStore.Audio.AudioColumns.IS_MUSIC);

    if (cursor != null) {

    while (cursor.moveToNext()) {

    Song song = new Song();

    song.song = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));

    song.singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));

    song.path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));

    song.duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

    song.size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));

    if (song.size > 1000 * 800) {

    if (song.song.contains("-")) {

    String[] str = song.song.split("-");

    song.singer = str[0];

    song.song = str[1];

    }

    list.add(song);

    }

    }

    cursor.close();

    }

    return list;

    }

    public static String formatTime(int time) {

    if (time / 1000 % 60 < 10) {

    return time / 1000 / 60 + ":0" + time / 1000 % 60;

    } else {

    return time / 1000 / 60 + ":" + time / 1000 % 60;

    }

    }

    }

    自定义存储音乐的Bean类

    public class Song {

    @Override

    public String toString() {

    return "Song{" +

    "singer='" + singer + '\'' +

    ", song='" + song + '\'' +

    ", path='" + path + '\'' +

    ", duration=" + duration +

    ", size=" + size +

    '}';

    }

    public String getSinger() {

    return singer;

    }

    public void setSinger(String singer) {

    this.singer = singer;

    }

    public String getSong() {

    return song;

    }

    public void setSong(String song) {

    this.song = song;

    }

    public String getPath() {

    return path;

    }

    public void setPath(String path) {

    this.path = path;

    }

    public int getDuration() {

    return duration;

    }

    public void setDuration(int duration) {

    this.duration = duration;

    }

    public long getSize() {

    return size;

    }

    public void setSize(long size) {

    this.size = size;

    }

    public Song() {

    this.singer = singer;

    this.song = song;

    this.path = path;

    this.duration = duration;

    this.size = size;

    }

    /**

    * 歌手

    */

    public String singer;

    /**

    * 歌曲名

    */

    public String song;

    /**

    * 歌曲的地址

    */

    public String path;

    /**

    * 歌曲长度

    */

    public int duration;

    /**

    * 歌曲的大小

    */

    public long size;

    }

    主页面实现音乐播放器功能

    public class MainActivity extends AppCompatActivity implements View.OnClickListener,SeekBar.OnSeekBarChangeListener, MediaPlayer.OnCompletionListener { private MediaPlayer mMediaPlayer; protected Button mPreviousBtn; protected Button mPlayBtn; protected Button mNextBtn; protected TextView mCurrentTimeTv; protected TextView mTotalTimeTv; protected SeekBar mSeekBar; private ListView mListView; private Listlist;

    private MyAdapter adapter;

    // 记录当前播放歌曲的位置

    private int mCurrentPosition;

    private Handler mHandler = new Handler(new Handler.Callback() {

    @Override

    public boolean handleMessage(Message msg) {

    // 展示给进度条和当前时间

    int progress = mMediaPlayer.getCurrentPosition();

    mSeekBar.setProgress(progress);

    mCurrentTimeTv.setText(parseTime(progress));

    // 继续定时发送数据

    updateProgress();

    return true;

    }

    });

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mMediaPlayer= new MediaPlayer();

    initView();

    }

    private void initView() {

    mListView = (ListView) findViewById(R.id.main_listview);

    mPreviousBtn = (Button) findViewById(R.id.previous_btn);

    mPreviousBtn.setOnClickListener(MainActivity.this);

    mPlayBtn = (Button) findViewById(R.id.play_btn);

    mPlayBtn.setOnClickListener(MainActivity.this);

    mNextBtn = (Button) findViewById(R.id.next_btn);

    mNextBtn.setOnClickListener(MainActivity.this);

    mCurrentTimeTv = (TextView) findViewById(R.id.current_time_tv);

    mTotalTimeTv = (TextView) findViewById(R.id.total_time_tv);

    mSeekBar = (SeekBar) findViewById(R.id.seek_bar);

    // SeekBar绑定监听器,监听拖动到指定位置

    mSeekBar.setOnSeekBarChangeListener(MainActivity.this);

    list = new ArrayList<>();

    list = MusicUtils.getMusicData(this);

    adapter = new MyAdapter(this,list);

    mListView.setAdapter(adapter);

    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override

    public void onItemClick(AdapterView adapterView, View view, int position, long l) {

    mCurrentPosition = position;

    changeMusic(mCurrentPosition);

    }

    });

    }

    // 切歌

    private void changeMusic(int position) {

    if (position < 0) {

    mCurrentPosition = position = list.size() - 1;

    } else if (position > list.size() - 1) {

    mCurrentPosition = position = 0;

    }

    if (mMediaPlayer == null) {

    mMediaPlayer = new MediaPlayer();

    // 绑定播放完毕监听器

    mMediaPlayer.setOnCompletionListener(this);

    }

    try {

    // 切歌之前先重置,释放掉之前的资源

    mMediaPlayer.reset();

    // 设置播放源

    mMediaPlayer.setDataSource(list.get(position).getPath());

    // 开始播放前的准备工作,加载多媒体资源,获取相关信息

    mMediaPlayer.prepare();

    // 开始播放

    mMediaPlayer.start();

    } catch (IOException e) {

    e.printStackTrace();

    Toast.makeText(this, "播放错误", Toast.LENGTH_SHORT).show();

    }

    // 切歌时重置进度条并展示歌曲时长

    mSeekBar.setProgress(0);

    mSeekBar.setMax(mMediaPlayer.getDuration());

    mTotalTimeTv.setText(parseTime(mMediaPlayer.getDuration()));

    updateProgress();

    }

    @Override

    public void onClick(View view) {

    if (view.getId() == R.id.previous_btn) {// 上一首

    changeMusic(--mCurrentPosition);

    } else if (view.getId() == R.id.play_btn) {// 播放/暂停

    // 首次点击播放按钮,默认播放第0首

    if (mMediaPlayer == null) {

    changeMusic(0);

    } else {

    playOrPause();

    }

    } else if (view.getId() == R.id.next_btn) {// 下一首

    changeMusic(++mCurrentPosition);

    }

    }

    // 播放或暂停

    private void playOrPause() {

    if (mMediaPlayer.isPlaying()) {

    mMediaPlayer.pause();

    } else {

    mMediaPlayer.start();

    }

    }

    private void updateProgress() {

    // 使用Handler每间隔1s发送一次空消息,通知进度条更新

    Message msg = Message.obtain();// 获取一个现成的消息

    mHandler.sendMessageDelayed(msg, INTERNAL_TIME);

    }

    private static final int INTERNAL_TIME = 1000;// 音乐进度间隔时间

    private String parseTime(int oldTime) {

    SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");// 时间格式

    String newTime = sdf.format(new Date(oldTime));

    return newTime;

    }

    @Override

    public void onCompletion(MediaPlayer mediaPlayer) {

    // 当歌曲播放完毕,切歌到下一首

    changeMusic(++mCurrentPosition);

    }

    @Override

    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override

    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override

    public void onStopTrackingTouch(SeekBar seekBar) {

    int progress = seekBar.getProgress();

    mMediaPlayer.seekTo(progress);

    }

    }

    List适配器实现item点击事件

    public class MyAdapter extends BaseAdapter { private Context context; private Listlist; public MyAdapter(MainActivity mainActivity, Listlist) {

    this.context = mainActivity;

    this.list = list;

    }

    @Override

    public int getCount() {

    return list.size();

    }

    @Override

    public Object getItem(int i) {

    return list.get(i);

    }

    @Override

    public long getItemId(int i) {

    return i;

    }

    @Override

    public View getView(final int i, View view, ViewGroup viewGroup) {

    ViewHolder holder = null;

    if (view == null) {

    holder = new ViewHolder();

    view = View.inflate(context, R.layout.item_music_listview, null);

    holder.song = (TextView) view.findViewById(R.id.item_mymusic_song);

    holder.singer = (TextView) view.findViewById(R.id.item_mymusic_singer);

    holder.duration = (TextView) view.findViewById(R.id.item_mymusic_duration);

    holder.position = (TextView) view.findViewById(R.id.item_mymusic_postion);

    view.setTag(holder);

    } else {

    holder = (ViewHolder) view.getTag();

    }

    holder.song.setText(list.get(i).song.toString());

    holder.singer.setText(list.get(i).singer.toString());

    int duration = list.get(i).duration;

    String time = MusicUtils.formatTime(duration);

    holder.duration.setText(time);

    holder.position.setText("");

    return view;

    }

    class ViewHolder{

    TextView song;

    TextView singer;

    TextView duration;

    TextView position;

    String parh;

    }

    }

    相关文章

      网友评论

          本文标题:读取手机内存音乐,使用MediaPlayer播放

          本文链接:https://www.haomeiwen.com/subject/wgnkvxtx.html