安卓音乐播放器

给你一囗甜甜゛ 提交于 2020-01-15 05:47:30

主界面

在这里插入图片描述

主界面布局

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <ListView
        android:id="@+id/lv"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="8"></ListView>

    <SeekBar
        android:id="@+id/sb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>

    <LinearLayout
        android:layout_weight="1.2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:id="@+id/ll">

        <ImageView
            android:id="@+id/img"
            android:background="@mipmap/ic_launcher"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"/>


        <ImageView
            android:id="@+id/type"
            android:layout_marginLeft="20dp"
            android:background="@drawable/ic_action_single"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_gravity="center"/>

        <ImageView
            android:id="@+id/upmusic"
            android:background="@drawable/ic_action_name"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"/>

        <ImageView
            android:id="@+id/play"
            android:background="@drawable/ic_action_start"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"/>

        <ImageView
            android:id="@+id/downmusic"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:background="@drawable/ic_action_next"
            android:layout_gravity="center"/>


    </LinearLayout>


</LinearLayout>


Activity内容

package com.cx.test;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

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 ListView lv;
    private LinearLayout ll;
    private SeekBar sb;
    private ImageView img;
    private ImageView type;
    private ImageView upmusic;
    private ImageView play;
    private ImageView downmusic;
    private int index=0;
    private int state=MusicState.ORDER;

    private MediaPlayer mediaPlayer=new MediaPlayer();
    private List<Music> list=new ArrayList<>();
    private boolean temp=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.lv);
        sb = (SeekBar) findViewById(R.id.sb);
        img = (ImageView) findViewById(R.id.img);
        type = (ImageView) findViewById(R.id.type);
        upmusic = (ImageView) findViewById(R.id.upmusic);
        play = (ImageView) findViewById(R.id.play);
        downmusic = (ImageView) findViewById(R.id.downmusic);
        ll = (LinearLayout) findViewById(R.id.ll);



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


        type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final PopupWindow popupWindow = new PopupWindow();
                View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_layout, null);
                popupWindow.setContentView(inflate);
                popupWindow.setWidth(300);
                popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);



                TextView order = inflate.findViewById(R.id.order);
                order.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        state=MusicState.ORDER;
                        type.setBackgroundResource(R.drawable.ic_action_typeorder);
                        popupWindow.dismiss();
                    }
                });
                TextView singless = inflate.findViewById(R.id.singless);
                singless.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        state=MusicState.SINGLE;
                        type.setBackgroundResource(R.drawable.ic_action_single);
                        popupWindow.dismiss();
                    }
                });
                TextView random = inflate.findViewById(R.id.random);
                random.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        state=MusicState.RANDOM;
                        type.setBackgroundResource(R.drawable.ic_action_typerandom);
                        popupWindow.dismiss();
                    }
                });
                popupWindow.setOutsideTouchable(true);
                popupWindow.showAsDropDown(ll,300,-400);


            }
        });


        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (temp){
                    mediaPlayer.start();
                    temp=false;
                    play.setBackgroundResource(R.drawable.ic_action_stop);


                }else {
                    mediaPlayer.pause();
                    temp=true;
                    play.setBackgroundResource(R.drawable.ic_action_start);
                }

            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index=position;
                play(position);
                play.setBackgroundResource(R.drawable.ic_action_stop);
                temp=true;
            }
        });


        downmusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playNext();

            }
        });

        upmusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (--index<1){
                    index=list.size()-1;
                }
                play(index);
            }
        });



        sb.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) {

            }
        });

    }

    private void playNext() {
        if (++index>list.size()-1){
            index=0;
        }
        play(index);
    }

    private void play(final int position) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(list.get(position).getPath());
            mediaPlayer.prepareAsync();

        } catch (IOException e) {
            e.printStackTrace();
        }

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();
                sb.setMax(mediaPlayer.getDuration());
                if (temp){
                    play.setBackgroundResource(R.drawable.ic_action_stop);
                    temp=false;
                }

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

                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {

                        switch (state){
                            case MusicState.ORDER:
                                playNext();
                                state=MusicState.ORDER;
                                break;

                            case MusicState.RANDOM:
                                int i = new Random().nextInt(list.size());
                                play(i);
                                state=MusicState.RANDOM;
                                break;

                            case MusicState.SINGLE:
                                play(position);
                                state=MusicState.SINGLE;
                                break;

                        }
                    }
                });

                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sb.setProgress(mediaPlayer.getCurrentPosition());
                            }
                        });
                    }
                },0,1);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode==111&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
            list=MusicUtills.getMusicDate(this);
            MyAdapter myAdapter = new MyAdapter(this,list);
            lv.setAdapter(myAdapter);


        }else {
            finish();
        }

    }

}


选项列表点击选择的常量

package com.cx.test;

public class MusicState {
    public static final int ORDER=0;
    public static final int SINGLE=1;
    public static final int RANDOM=2;
}


选项框列表布局

<?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="vertical"
    android:background="#DA3971">

    <TextView
        android:id="@+id/order"
        android:text="顺序播放"
        android:textColor="#fff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/singless"
        android:text="单曲播放"
        android:textColor="#fff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

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



</LinearLayout>


歌曲类Bean

package com.cx.test;

public class Music {

    private String musicName;
    private String singer;
    private int time;
    private String path;
    private long size;

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    public Music(String musicName, String singer, int time, String path, long size) {
        this.musicName = musicName;
        this.singer = singer;
        this.time = time;
        this.path = path;
        this.size = size;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public Music() {
        super();
    }

    public String getMusicName() {
        return musicName;
    }

    public void setMusicName(String musicName) {
        this.musicName = musicName;
    }

    public String getSinger() {
        return singer;
    }

    public void setSinger(String singer) {
        this.singer = singer;
    }

    public int getTime() {
        return time;
    }

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

歌曲工具方法

package com.cx.test;

import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.widget.Toast;

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

public class MusicUtills {

    public static List<Music> getMusicDate(Context context){
        List<Music> list=new ArrayList<>();
        Cursor query = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        if (query!=null){

            while (query.moveToNext()){
                Music music = new Music();
                music.setMusicName(query.getString(query.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
                music.setSinger(query.getString(query.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)));
                music.setTime(query.getInt(query.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)));
                music.setPath(query.getString(query.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
                music.setSize(query.getLong(query.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)));
                if (music.getSize()>=1000*600){
                    list.add(music);
                }


            }
            query.close();

        }else {
            Toast.makeText(context, "没有文件", Toast.LENGTH_SHORT).show();
        }
        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;
        }
    }

}

ListView显示布局

<?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">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="10dp">

        <ImageView
            android:id="@+id/imgs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@mipmap/ic_launcher"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_marginLeft="10dp">
            <TextView
                android:id="@+id/name"
                android:text="你的名字"
                android:textSize="20dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                />

            <TextView
                android:id="@+id/singer"
                android:text="刘德华"
                android:layout_marginTop="5dp"
                android:layout_gravity="center"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />


        </LinearLayout>



        <TextView
            android:id="@+id/timelong"
            android:text="3:25"
            android:layout_marginLeft="120dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"/>

    </LinearLayout>




</LinearLayout>




BaseAdapter适配器

package com.cx.test;

import android.content.Context;
import android.media.MediaPlayer;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MyAdapter extends BaseAdapter {

    private List<Music> list;
    private Context context;
    private MediaPlayer mediaPlayer=new MediaPlayer();

    public MyAdapter(MainActivity mainActivity, List<Music> list) {
        this.context = mainActivity;
        this.list = list;
    }


    @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 view, ViewGroup parent) {
        ViewHuilder viewHuilder = null;
        if (view==null){
            viewHuilder=new ViewHuilder();
            view=View.inflate(context,R.layout.show_layout,null);
            viewHuilder.name=view.findViewById(R.id.name);
            viewHuilder.singer=view.findViewById(R.id.singer);
            viewHuilder.timelong=view.findViewById(R.id.timelong);
            view.setTag(viewHuilder);
        }else {
            viewHuilder = (ViewHuilder) view.getTag();
        }

        viewHuilder.name.setText(list.get(position).getMusicName());
        viewHuilder.singer.setText(list.get(position).getSinger());

        int time = list.get(position).getTime();
        String timmer=MusicUtills.formatTime(time);
        viewHuilder.timelong.setText(timmer);


        return view;
    }
}

class ViewHuilder{
     TextView name;
     TextView singer;
     TextView timelong;
}


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