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();
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,992评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,212评论 3 388
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,535评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,197评论 1 287
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,310评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,383评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,409评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,191评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,621评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,910评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,084评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,763评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,403评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,083评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,318评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,946评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,967评论 2 351

推荐阅读更多精彩内容