音乐播放器

≡放荡痞女 提交于 2020-01-10 00:25:57

MainActivity

package com.example.mymusic;

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

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    private List<Music> musicList;
    private ListView lv;
    private ImageView sequence;
    private ImageView back;
    private ImageView sp;
    private SeekBar seek;
    private Timer timer;
    private ImageView next;
    private static final String TAG = "MainActivity";
    private MediaPlayer mediaPlayer;
    private boolean flag = false;
    private int index = 0;
    private TextView musicName;
    private LinearLayout ll;
    private int playType = 2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10086);
        //初始化资源
        inputMag();

        //给设置listview监听
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                play(position);

            }
        });
        sequence.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置弹窗
                final PopupWindow popupMenu = new PopupWindow();
                View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.menu_layout, null);
                popupMenu.setContentView(inflate);
                popupMenu.setWidth(200);
                popupMenu.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                popupMenu.setOutsideTouchable(true);
                popupMenu.showAsDropDown(ll, -200, -200);

                TextView s = inflate.findViewById(R.id.s);
                TextView r = inflate.findViewById(R.id.r);
                TextView o = inflate.findViewById(R.id.o);
                //弹窗设置监听,改变监听模式
                s.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        playType = Finshs.S;
                        sequence.setImageResource(R.drawable.ic_action_onley);
                        popupMenu.dismiss();
                    }
                });
                r.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        playType = Finshs.R;
                        sequence.setImageResource(R.drawable.ic_action_remode);
                        popupMenu.dismiss();
                    }
                });
                o.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        playType = Finshs.O;
                        sequence.setImageResource(R.drawable.ic_action_order);
                        popupMenu.dismiss();
                    }
                });

            }
        });

//进度条
        seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //下一首
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (++index > musicList.size() - 1) {
                    index = 0;
                }
                play(index);
            }
        });
        //上一首
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (--index < 0) {
                    index = 0;
                }
                play(index);
            }
        });
        //暂停 开始
        sp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer.isPlaying()) {
                    sp.setImageResource(R.drawable.ic_action_play);
                    mediaPlayer.pause();
                } else {
                    if (!flag) {
                        play(index);
                    }
                    sp.setImageResource(R.drawable.ic_action_stop);
                    mediaPlayer.start();
                }
            }
        });
    }

    //初始化
    private void inputMag() {
        lv = (ListView) findViewById(R.id.lv);
        sequence = (ImageView) findViewById(R.id.sequence);
        back = (ImageView) findViewById(R.id.back);
        sp = (ImageView) findViewById(R.id.sp);
        seek = (SeekBar) findViewById(R.id.seek);
        next = (ImageView) findViewById(R.id.next);
        musicList = new ArrayList<>();
        mediaPlayer = new MediaPlayer();
        musicName = (TextView) findViewById(R.id.music_name);
        timer = new Timer();
        ll = (LinearLayout) findViewById(R.id.ll);
    }

    //播放设置
    private void play(int position) {
        mediaPlayer.reset();
        sp.setImageResource(R.drawable.ic_action_stop);
        try {
            if (position < 0) {
                index = 0;
                position = index;
            }
            if (position > musicList.size() - 1) {
                index = 0;
                position = index;
            }
            musicName.setText(musicList.get(position).getName());
            Log.i(TAG, "play: " + musicList.get(position).getLoction());
            mediaPlayer.setDataSource(musicList.get(position).getLoction());
            mediaPlayer.prepareAsync();
            //监听异步加载
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    flag = true;
                    mediaPlayer.start();
                    //获取文件的时常并赋值
                    seek.setMax(mediaPlayer.getDuration());

                }
            });
            //当歌曲播放完之后调用
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //顺序
                    if (playType == Finshs.O) {
                        play(++index);
                    }
                    //随机
                    if (playType == Finshs.R) {
                        play(new Random().nextInt(musicList.size()));
                    }
                    //单曲循环
                    if (playType == Finshs.S) {
                        play(index);
                    }
                }
            });
            //实时更新进度条
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //获取但钱歌曲的播放位置添加至进度条
                    seek.setProgress(mediaPlayer.getCurrentPosition());
                }
            }, 0, 1000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

    //获取内存歌曲的将填充到集合中
    private void inmusic() {
        ContentResolver contentResolver = getContentResolver();
        Uri parse = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor query = contentResolver.query(parse, null, null, null, null);
        while (query.moveToNext()) {
            String name = query.getString(query.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String mag = query.getString(query.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            String time = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DURATION));
            String loction = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DATA));
            //过滤小于一分钟的音频文件
            if (Integer.parseInt(time) <= 1000 * 60) {
                continue;
            }
            musicList.add(new Music(name, time, mag, loction));
        }
        lv.setAdapter(new MyAdapter());

    }

    //适配器
    class MyAdapter extends BaseAdapter {

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

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HV hv;
            if (convertView == null) {
                hv = new HV();
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.music_layout, null);
                hv.mag = convertView.findViewById(R.id.mag);
                hv.name = convertView.findViewById(R.id.name);
                hv.time = convertView.findViewById(R.id.time);
                hv.img = convertView.findViewById(R.id.img);
                convertView.setTag(hv);
            } else {
                hv = (HV) convertView.getTag();
            }
            hv.name.setText(musicList.get(position).getName());
            hv.mag.setText(musicList.get(position).getMag());
            String time = musicList.get(position).getTime();
            int minute = Integer.parseInt(time) / 1000 / 60;
            int second = (Integer.parseInt(time) / 1000 % 60);
            String musicTime = null;
            if (second >= 10) {
                musicTime = minute + ":" + second;
            } else {
                musicTime = minute + ":0" + second;
            }
            hv.time.setText(musicTime);
            return convertView;
        }

        class HV {
            TextView name;
            TextView time;
            TextView mag;
            ImageView img;

        }
    }
}

常量

package com.example.mymusic;

public class Finshs {
    //单曲循环
    public static final int S = 0;
    //随机
    public static final int R = 1;
    //顺序
    public static final int O = 2;
}

自定义Bean类

package com.example.mymusic;

public class Music {
    String name;
    String time;
    String mag;
    String loction;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getMag() {
        return mag;
    }

    public void setMag(String mag) {
        this.mag = mag;
    }

    public String getLoction() {
        return loction;
    }

    public void setLoction(String loction) {
        this.loction = loction;
    }

    public Music(String name, String time, String mag, String loction) {
        this.name = name;
        this.time = time;
        this.mag = mag;
        this.loction = loction;
    }
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:orientation="vertical">

    <TextView
        android:id="@+id/s"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="单曲循环"
        android:textColor="#fff" />

    <TextView
        android:id="@+id/r"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="随机播放"
        android:textColor="#fff" />

    <TextView
        android:id="@+id/o"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顺序播放"
        android:textColor="#fff" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/img"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/ic_launcher_foreground" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="123" />

        <TextView
            android:id="@+id/time"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_gravity="right"
            android:layout_weight="1 "
            android:text="123" />

        <TextView
            android:id="@+id/mag"
            android:layout_width="wrap_content"

            android:layout_height="0dp"
            android:layout_weight="1 "
            android:text="123" />

    </LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="9"
        android:background="#00BCD4"></ListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1.2"
        android:background="#555">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:src="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <SeekBar
                android:id="@+id/seek"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/music_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <LinearLayout
                android:id="@+id/ll"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center">


                <ImageView
                    android:id="@+id/sequence"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:src="@drawable/ic_action_order" />

                <ImageView
                    android:id="@+id/back"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:src="@drawable/ic_action_back" />

                <ImageView
                    android:id="@+id/sp"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:src="@drawable/ic_action_play" />

                <ImageView
                    android:id="@+id/next"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:src="@drawable/ic_action_next" />

            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!