2019-08-21音乐播放器

清单文件中添加权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Main布局代码

<RelativeLayout 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:padding="20dp"
    >

    <RelativeLayout
        android:id="@+id/bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        >

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minLines="1" />
        <Button
            android:id="@+id/last"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="last"
            />
        <Button
            android:id="@+id/play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/last"
            android:text="play"
            />
        <Button
            android:id="@+id/stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/play"
            android:text="stop"
            />

        <Button
            android:id="@+id/next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/stop"
            android:layout_centerVertical="true"
            android:text="next"
            />
        <SeekBar
            android:id="@+id/progress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/play"
            android:layout_marginTop="20dp"/>

    </RelativeLayout>
    <RelativeLayout
        android:id="@+id/top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/bendi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="加载本地音乐"
            />
        <Button
            android:id="@+id/wangluo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="加载网络音乐"
            />
    </RelativeLayout>
    <ListView
        android:id="@+id/list1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/top"
        android:layout_above="@id/bottom"
        />

</RelativeLayout>

musiclayout适配器布局代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    >

    <TextView
        android:id="@+id/music_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="未知歌曲"/>
    <TextView
        android:id="@+id/person_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/music_name"
        android:textSize="16dp"
        android:text="未知歌手"/>
    <TextView
        android:id="@+id/music_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:textSize="18dp"
        android:text="歌曲时长"/>
</RelativeLayout>

实体类

public class musicData {
    String title;
    String data;
    String artist;
    long duration;
    long size;
    int sort;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    public long getSize() {
        return size;
    }

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

    public int getSort() {
        return sort;
    }

    public void setSort(int sort) {
        this.sort = sort;
    }
}

适配器代码

public class MusicAdapter extends BaseAdapter {
    List<musicData> datalist;
    LayoutInflater layoutInflater;
    Context context;

    public MusicAdapter(List<musicData> datalist, Context context) {
        this.datalist = datalist;
        this.layoutInflater = LayoutInflater.from(context);
        this.context = context;
    }

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

    @Override
    public Object getItem(int i) {
        return datalist.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        viewHolder viewHolder;
        if(view==null){
            view= layoutInflater.inflate(R.layout.musiclayout, null);
            viewHolder=new viewHolder();
            viewHolder.yi=view.findViewById(R.id.music_name);
            viewHolder.er=view.findViewById(R.id.music_time);
            viewHolder.three=view.findViewById(R.id.person_name);
            view.setTag(viewHolder);
        }
        else{
            viewHolder= (viewHolder) view.getTag();
        }

        viewHolder.yi.setText(datalist.get(i).title);
        long duration = datalist.get(i).getDuration();
        long fen=duration/60000;
        long miao = (duration%60000)/1000;
        viewHolder.er.setText(fen+"分"+miao+"秒");
        viewHolder.three.setText(datalist.get(i).artist);

        return view;
    }
    class viewHolder{
           TextView yi,er,three;
    }
}

Activity代码

public class MainActivity extends AppCompatActivity {
    final int CANT_PLAY = 0;
    final int CAN_PLAY = 1;
    final int PLAYING = 2;
    final int PAUSE = 3;
    final int CHANGE = 4;
    MusicAdapter musicAdapter;
    int playTime = 0;

    int isCanStart = CANT_PLAY;//播放状态0:未准备完成 1准备完成 2播放中 3暂停 4换曲

    Button play, stop, next, last, bendi;
    ListView music_list;//播放列表
    TextView text1;
    SeekBar progress;
    musicData nowMusic;
    List<musicData> datalist;
    MediaPlayer mediaPlayer;//播放器


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
//                    Log.e("#####", "handler" + playTime);
                    progress.setProgress(playTime);
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        datalist=new ArrayList<>();
        text1 = findViewById(R.id.name);
        music_list = findViewById(R.id.list1);
        progress = findViewById(R.id.progress);
        play = findViewById(R.id.play);
        stop = findViewById(R.id.stop);
        next = findViewById(R.id.next);
        last = findViewById(R.id.last);
        bendi = findViewById(R.id.bendi);
        mediaPlayer = new MediaPlayer();
        nowMusic = new musicData();
        //Environment.getExternalStorageDirectory()

        music_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                nowMusic = datalist.get(i);
                musicStop();
                isCanStart = CHANGE;
                initPlayer(nowMusic);
            }
        });

        progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int aa = 0;

            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                Log.i("######", "onProgressChanged=" + i);
                aa = i;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.i("######", "onStartTrackingTouch=");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.i("######", "onStopTrackingTouch=");
                playTime = aa;
                mediaPlayer.seekTo(playTime);
            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                Log.e("####", "播放完毕");
                musicStop();
                isCanStart = CHANGE;
                int num2 = nowMusic.getSort();
                if (datalist == null) {
                    Log.e("####", "完毕");
                    return;
                }
                if (num2 == datalist.size() - 1) {
                    num2 = 0;
                } else {
                    num2 = num2 + 1;
                }
                nowMusic = datalist.get(num2);
                initPlayer(nowMusic);
            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCanStart == CANT_PLAY) {
                    Toast.makeText(MainActivity.this, "没有准备好音频文件啊", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!mediaPlayer.isPlaying()) {
                    musicPlay();
                } else {
                    isCanStart = PAUSE;
                    mediaPlayer.pause();
                }
//                try {
//                    if (mediaPlayer == null) {
//                        mediaPlayer = new MediaPlayer();
//                    }
//                    mediaPlayer.setDataSource("/sdcard/Music/aaa");
//                    mediaPlayer.prepareAsync();
//                    mediaPlayer.setOnPreparedListener(new musiclistener());
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                mediaPlayer.stop();
                musicStop();
                initPlayer(nowMusic);
            }
        });
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCanStart == CANT_PLAY) {
                    Toast.makeText(MainActivity.this, "音频文件未准备好", Toast.LENGTH_SHORT).show();
                    return;
                }
                musicStop();
                isCanStart = CHANGE;
                int num2 = nowMusic.getSort();
                if (num2 == datalist.size() - 1) {
                    num2 = 0;
                } else {
                    num2 = num2 + 1;
                }
                nowMusic = datalist.get(num2);
                initPlayer(nowMusic);
            }
        });
        last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCanStart == CANT_PLAY) {
                    Toast.makeText(MainActivity.this, "音频文件未准备好", Toast.LENGTH_SHORT).show();
                    return;
                }
                musicStop();
                isCanStart = CHANGE;
                int num = nowMusic.getSort();
                if (num == 0) {
                    num = datalist.size() - 1;
                } else {
                    num = num - 1;
                }
                nowMusic = datalist.get(num);
                initPlayer(nowMusic);

            }
        });
        bendi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String acc = "android.permission.READ_EXTERNAL_STORAGE";
                checkAccess(acc, 1);
            }
        });

        int currentPosition = mediaPlayer.getCurrentPosition();//当前播放时长
        int duration = mediaPlayer.getDuration();//总时长


    }

    private void checkAccess(String acc, int i) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            int hasAccess = ContextCompat.checkSelfPermission(getApplication(), acc);
            if (ContextCompat.checkSelfPermission(getApplication(), acc) == 0) {
                music();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{acc, "android.permission.WRITE_EXTERNAL_STORAGE"}, i);
            }
        } else {
            Log.e("TAG", "非6.0直接使用");
            music();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            music();
        } else {
            // TODO: 2019/6/15 未获得授权执行的操作
            finish();
        }
    }

    private void music() {
//        Log.e("TAG", "有音乐资源啊");
        ContentResolver resolver = getContentResolver();
        // Uri uri1 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;//音频的URI
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        Cursor cursor = resolver.query(uri, null, null, null, null);
        if (cursor == null || cursor.getCount() <= 0) {
            Log.e("TAG", "没有音乐资源啊");
            return;
        }
        datalist = new ArrayList<>();
        int a = 0;
        while (cursor.moveToNext()) {
            musicData musicData = new musicData();
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));


            musicData.setTitle(title);
            musicData.setArtist(artist);
            musicData.setData(data);
            musicData.setDuration(duration);
            musicData.setSize(size);
            musicData.setSort(a);
            a++;
            datalist.add(musicData);
            Log.e("###", "音乐: " + title + ":" + data + ":" + artist + ":" + duration + ":" + size);
        }
        musicAdapter = new MusicAdapter(datalist, this);
        music_list.setAdapter(musicAdapter);

        nowMusic = datalist.get(0);
        initPlayer(nowMusic);
    }

    private boolean initPlayer(musicData data) {
        Log.e("#####", nowMusic.getTitle() + "");
        if (isCanStart != CHANGE) {
            isCanStart = CANT_PLAY;
        }
        String filename = data.getData();
        File file = new File(filename);

        try {
            mediaPlayer.setDataSource(file.getPath());
            Log.e("播放器", file.toString());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new musiclistener());
            text1.setText(nowMusic.getTitle());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    class musiclistener implements MediaPlayer.OnPreparedListener {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            if (isCanStart == CHANGE) {
                musicPlay();
            } else {
                isCanStart = CAN_PLAY;
            }
//            mediaPlayer.start();
        }

    }

    private void musicPlay() {
        isCanStart = PLAYING;
        mediaPlayer.seekTo(playTime);
        mediaPlayer.start();
        int totalTime = Math.round(mediaPlayer.getDuration() / 1000);
        String str = String.format("%02d:%02d", totalTime / 60, totalTime % 60);
        text1.setText(nowMusic.getTitle() + str);
        progress.setMax(mediaPlayer.getDuration());
        new myThread().start();
    }

    private void musicStop() {
        isCanStart = CANT_PLAY;
        mediaPlayer.stop();
        mediaPlayer.reset();
        playTime = 0;
        progress.setProgress(0);
    }

    private class myThread extends Thread {
        @Override
        public void run() {
            while (mediaPlayer.isPlaying()) {
                playTime = mediaPlayer.getCurrentPosition();
                Log.e("TAG", playTime + "");
                handler.sendEmptyMessage(100);
                if (playTime > mediaPlayer.getDuration()) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容