清單文件中添加權(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();
}
}
}