2019-08-21音樂播放器

清單文件中添加權(quán)限

<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="加載網(wǎng)絡(luò)音樂"
            />
    </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="歌曲時(shí)長"/>
</RelativeLayout>

實(shí)體類

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;//播放狀態(tài)0:未準(zhǔn)備完成 1準(zhǔn)備完成 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, "沒有準(zhǔn)備好音頻文件啊", 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, "音頻文件未準(zhǔn)備好", 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, "音頻文件未準(zhǔn)備好", 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();//當(dāng)前播放時(shí)長
        int duration = mediaPlayer.getDuration();//總時(shí)長


    }

    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 未獲得授權(quán)執(zhí)行的操作
            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();
        }
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末负蠕,一起剝皮案震驚了整個(gè)濱河市偿乖,隨后出現(xiàn)的幾起案子系任,更是在濱河造成了極大的恐慌筑凫,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,294評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吨艇,死亡現(xiàn)場(chǎng)離奇詭異躬它,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)东涡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,493評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門虑凛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人软啼,你說我怎么就攤上這事⊙幽” “怎么了祸挪?”我有些...
    開封第一講書人閱讀 157,790評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長贞间。 經(jīng)常有香客問我贿条,道長,這世上最難降的妖魔是什么增热? 我笑而不...
    開封第一講書人閱讀 56,595評(píng)論 1 284
  • 正文 為了忘掉前任整以,我火速辦了婚禮,結(jié)果婚禮上峻仇,老公的妹妹穿的比我還像新娘公黑。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,718評(píng)論 6 386
  • 文/花漫 我一把揭開白布凡蚜。 她就那樣靜靜地躺著人断,像睡著了一般。 火紅的嫁衣襯著肌膚如雪朝蜘。 梳的紋絲不亂的頭發(fā)上恶迈,一...
    開封第一講書人閱讀 49,906評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音谱醇,去河邊找鬼暇仲。 笑死,一個(gè)胖子當(dāng)著我的面吹牛副渴,可吹牛的內(nèi)容都是我干的奈附。 我是一名探鬼主播,決...
    沈念sama閱讀 39,053評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼佳晶,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼桅狠!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起轿秧,我...
    開封第一講書人閱讀 37,797評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤中跌,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后菇篡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體漩符,經(jīng)...
    沈念sama閱讀 44,250評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,570評(píng)論 2 327
  • 正文 我和宋清朗相戀三年驱还,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了嗜暴。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,711評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡议蟆,死狀恐怖闷沥,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情咐容,我是刑警寧澤舆逃,帶...
    沈念sama閱讀 34,388評(píng)論 4 332
  • 正文 年R本政府宣布,位于F島的核電站戳粒,受9級(jí)特大地震影響路狮,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜蔚约,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,018評(píng)論 3 316
  • 文/蒙蒙 一奄妨、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧苹祟,春花似錦砸抛、人聲如沸评雌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,796評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽柳骄。三九已至,卻和暖如春箕般,著一層夾襖步出監(jiān)牢的瞬間耐薯,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,023評(píng)論 1 266
  • 我被黑心中介騙來泰國打工丝里, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留曲初,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,461評(píng)論 2 360
  • 正文 我出身青樓杯聚,卻偏偏與公主長得像臼婆,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子幌绍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,595評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容