您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關Android10.0如何實現本地音樂播放?,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
本篇文章僅是Android小白在寫一個小程序,內容僅供參考,有很多不足之處希望各位大神指出,文章末尾有整個項目的下載,不需要幣,只求幫你們解決到問題的同時收獲到一顆小小的贊。這個項目中還有很多不足的地方,如:在按鍵中設置圖片文字,這些正常的應該交給Handler處理,我只是粗略地完成這個項目。測試環境:Android10.0。實現:自動播放下一首,正常音樂的功能,全屏顯示。
Android10.0是內外分存了的,應用是沒有權限讀取內存的,需要在配置文件中application中加上屬性:android:requestLegacyExternalStorage=“true”,不加可能可以讀取歌曲,但是無法播放。
截圖顯示不同是因為這不是同一時間截的,只是一個效果圖
①先在AndroidManifest文件里面配置權限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
②目前基本上的手機使用靜態權限是不夠的,需要動態獲取權限,因此需要在MainActivity里面動態獲取,在onCreate方法里調用方法
private void check(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); Log.d(TAG,"---------------------寫權限不夠-----------------"); } if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED ){ requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2); Log.d(TAG,"---------------------讀權限不夠-----------------"); } } }
③再去實現權限的回調方法,與Activity的onCreate方法是同一級別的
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "---------------------寫權限夠了-----------------------------"); } break; case 2: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "---------------------讀權限夠了-----------------------------"); } break; } }
④創建一個工具類Mp3Info,用來保存音樂信息的,里面主要是一些get和set方法
public class Mp3Info { private String url;//路徑 private String title;//歌曲名 private String artist;//藝術家 private long duration;//歌曲時長 private long id; private long album;//專輯圖片 }
⑤創建一個MusicUtil類,通過ContentPorvider的接口獲取歌曲信息
public class MusicUtil { //獲取專輯封面的UI private static final String TAG="MusicUtil"; private static final Uri albumArtUri=Uri.parse("content://media/external/audio/albumart"); //生成歌曲列表 public static List<Mp3Info> getMp3InfoList(Context context){ Cursor cursor=context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,null); List<Mp3Info> mp3InfoList=new ArrayList<>(); while(cursor.moveToNext()){ Mp3Info mp3Info=new Mp3Info(); mp3Info.setUrl(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));//path mp3Info.setTitle(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))); mp3Info.setArtist(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))); mp3Info.setDuration(cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))); mp3Info.setId(cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID))); mp3Info.setAlbum(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID))); mp3InfoList.add(mp3Info); } return mp3InfoList; } //格式化時間,轉換為分/秒 public static String formatTime(long time){ String min = time / (1000 * 60) + ""; String sec = time % (1000 * 60) + ""; if (min.length() < 2) { min = "0" + time / (1000 * 60) + ""; } else { min = time / (1000 * 60) + ""; } if (sec.length() == 4) { sec = "0" + (time % (1000 * 60)) + ""; } else if (sec.length() == 3) { sec = "00" + (time % (1000 * 60)) + ""; } else if (sec.length() == 2) { sec = "000" + (time % (1000 * 60)) + ""; } else if (sec.length() == 1) { sec = "0000" + (time % (1000 * 60)) + ""; } return min + ":" + sec.trim().substring(0, 2); } //獲取專輯圖片,目前是只能獲取手機自帶歌曲的專輯圖片,如果手機有酷狗,qq音樂之類的,可能無法獲取專輯圖片 //因為他們的uri不知道。 public Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefalut, boolean small){ if(album_id < 0) { if(song_id < 0) { Bitmap bm = getArtworkFromFile(context, song_id, -1); if(bm != null) { return bm; } } if(allowdefalut) { return getDefaultArtwork(context, small); } return null; } ContentResolver res = context.getContentResolver(); Uri uri = ContentUris.withAppendedId(albumArtUri, album_id); if(uri != null) { InputStream in = null; try { in = res.openInputStream(uri); BitmapFactory.Options options = new BitmapFactory.Options(); //先制定原始大小 options.inSampleSize = 1; //只進行大小判斷 options.inJustDecodeBounds = true; //調用此方法得到options得到圖片的大小 BitmapFactory.decodeStream(in, null, options); /** 我們的目標是在你N pixel的畫面上顯示。 所以需要調用computeSampleSize得到圖片縮放的比例 **/ /** 這里的target為800是根據默認專輯圖片大小決定的,800只是測試數字但是試驗后發現完美的結合 **/ if(small){ options.inSampleSize = computeSampleSize(options, 40); } else{ options.inSampleSize = computeSampleSize(options, 600); } // 我們得到了縮放比例,現在開始正式讀入Bitmap數據 options.inJustDecodeBounds = false; options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; in = res.openInputStream(uri); return BitmapFactory.decodeStream(in, null, options); } catch (FileNotFoundException e) { Bitmap bm = getArtworkFromFile(context, song_id, album_id); if(bm != null) { if(bm.getConfig() == null) { bm = bm.copy(Bitmap.Config.RGB_565, false); if(bm == null && allowdefalut) { return getDefaultArtwork(context, small); } } } else if(allowdefalut) { bm = getDefaultArtwork(context, small); } return bm; } finally { try { if(in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } } return null; } /** * 從文件當中獲取專輯封面位圖 * @param context * @param songid * @param albumid * @return */ private static Bitmap getArtworkFromFile(Context context, long songid, long albumid){ Bitmap bm = null; if(albumid < 0 && songid < 0) { throw new IllegalArgumentException("---------------------"+TAG+"Must specify an album or a song id"); } try { BitmapFactory.Options options = new BitmapFactory.Options(); FileDescriptor fd = null; if(albumid < 0){ Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart"); ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); if(pfd != null) { fd = pfd.getFileDescriptor(); } } else { Uri uri = ContentUris.withAppendedId(albumArtUri, albumid); ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); if(pfd != null) { fd = pfd.getFileDescriptor(); } } options.inSampleSize = 1; // 只進行大小判斷 options.inJustDecodeBounds = true; // 調用此方法得到options得到圖片大小 BitmapFactory.decodeFileDescriptor(fd, null, options); // 我們的目標是在800pixel的畫面上顯示 // 所以需要調用computeSampleSize得到圖片縮放的比例 options.inSampleSize = 100; // 我們得到了縮放的比例,現在開始正式讀入Bitmap數據 options.inJustDecodeBounds = false; options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; //根據options參數,減少所需要的內存 bm = BitmapFactory.decodeFileDescriptor(fd, null, options); } catch (FileNotFoundException e) { e.printStackTrace(); } return bm; } /** * 獲取默認專輯圖片 * @param context * @return */ @SuppressLint("ResourceType") public static Bitmap getDefaultArtwork(Context context, boolean small) { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.RGB_565; if(small){ //返回小圖片 //return BitmapFactory.decodeStream(context.getResources().openRawResource(R.drawable.default_picture), null, opts); } return BitmapFactory.decodeStream(context.getResources().openRawResource(R.drawable.default_picture), null, opts); } /** * 對圖片進行合適的縮放 * @param options * @param target * @return */ public static int computeSampleSize(BitmapFactory.Options options, int target) { int w = options.outWidth; int h = options.outHeight; int candidateW = w / target; int candidateH = h / target; int candidate = Math.max(candidateW, candidateH); if(candidate == 0) { return 1; } if(candidate > 1) { if((w > target) && (w / candidate) < target) { candidate -= 1; } } if(candidate > 1) { if((h > target) && (h / candidate) < target) { candidate -= 1; } } return candidate; } }
⑥為列表設置adapter,新建一個MyAdapter類繼承BaseAdapter,然后在重寫的getView里面設置顯示的控件
@Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView==null){ holder=new ViewHolder(); convertView=View.inflate(context, R.layout.list_item,null); holder.tv_title=convertView.findViewById(R.id.tv_title); holder.tv_artist=convertView.findViewById(R.id.tv_artist); holder.tv_duration=convertView.findViewById(R.id.tv_duration); holder.tv_position=convertView.findViewById(R.id.tv_position); convertView.setTag(holder); }else { holder= (ViewHolder) convertView.getTag(); } holder.tv_title.setText(list.get(position).getTitle()); holder.tv_artist.setText(list.get(position).getArtist()); long duration = list.get(position).getDuration(); String time= MusicUtil.formatTime(duration); holder.tv_duration.setText(time); holder.tv_position.setText(position+1+""); if(currentItem == position){ holder.tv_title.setSelected(true); holder.tv_position.setSelected(true); holder.tv_duration.setSelected(true); holder.tv_artist.setSelected(true); }else{ holder.tv_title.setSelected(false); holder.tv_position.setSelected(false); holder.tv_duration.setSelected(false); holder.tv_artist.setSelected(false); } return convertView; } class ViewHolder{ TextView tv_title;//歌曲名 TextView tv_artist;//歌手 TextView tv_duration;//時長 TextView tv_position;//序號 }
使用的是bindService,這樣Service的生命周期就和Activity的生命周期綁定在一起了。創建一個MusicService。注意:銷毀Service的時候需要將音樂對象release。
①Service實現功能,在onBind方法里面實例化音樂播放對象
@Override public IBinder onBind(Intent intent) { Log.d(TAG,"onBind is call"); myBinder=new MyBinder(); return myBinder; }
②在MyBinder()里面實現音樂的各種功能,使用的是內部類,初始化部分請看源代碼包
public class MyBinder extends Binder{ private int index=0;//歌曲索引 //播放音樂 public void playMusic(int index){ this.index=index; try { File file=new File(list.get(this.index).getUrl()); if(!file.exists()){ Log.d(TAG,"------------------------------文件不存在------------------------------"); return ; }else{ Log.d(TAG,"------------------------------文件:"+file.getPath()+"存在 ------------------------------"); } if(mediaPlayer!=null){ mediaPlayer.reset(); mediaPlayer.release(); } mediaPlayer=new MediaPlayer(); String str=list.get(this.index).getUrl(); mediaPlayer.setDataSource(str); Log.d(TAG,list.get(this.index).getUrl()+""); mediaPlayer.prepare(); mediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } } //暫停音樂 public void pauseMusic(){ if(mediaPlayer.isPlaying()){ mediaPlayer.pause(); } } //關閉音樂 public void closeMusic(){ if(mediaPlayer!=null){ mediaPlayer.release(); } } //下一首 public void nextMusic(){ if(index>=list.size()-1){ this.index=0; }else{ this.index+=1; } playMusic(this.index); } //上一首 public void preciousMusic(){ if(index<=0){ this.index=list.size()-1; }else{ this.index-=1; } playMusic(this.index); } //獲取歌曲時長 public int getProgress(int dex){ return (int)list.get(dex).getDuration(); } public int getProgress(){ return (int)list.get(index).getDuration(); } //獲取當前播放位置 public int getPlayPosition(){ return mediaPlayer.getCurrentPosition(); } //移動到當前點播放 public void seekToPosition(int m){ mediaPlayer.seekTo(m); } }
③在MainActivity里面綁定
a.先實例化一個ServiceConnection對象
private ServiceConnection connection=new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { myBinder= (MusicService.MyBinder) service; seekBar.setMax(myBinder.getProgress()); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { //這里是判斷進度條移動是不是用戶所為 if(fromUser){ myBinder.seekToPosition(seekBar.getProgress()); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); handler.post(runnable); Log.d(TAG, "Service與Activity已連接"); } @Override public void onServiceDisconnected(ComponentName name) { } };
b.還需要一個handler來控制ui組件的變化,實例化放在了onCreate方法里面。
c.用一個Runnable對象進行seekbar的前進
private Runnable runnable=new Runnable() { @Override public void run() { seekBar.setProgress(myBinder.getPlayPosition()); tv_leftTime.setText(time.format(myBinder.getPlayPosition())+""); tv_rightTime.setText(time.format(myBinder.getProgress()-myBinder.getPlayPosition())+""); if(myBinder.getProgress()-myBinder.getPlayPosition()<1000){//時間不夠了自動觸發下一首 runOnUiThread(new Runnable() {//使用ui線程來觸發按鍵點擊事件,不知道這樣有沒有什么危害 @Override public void run() { ib_next.performClick(); } }); } handler.postDelayed(runnable,1000); } };
d.在onCreate方法里進行綁定
MediaServiceIntent =new Intent(this,MusicService.class);//MediaServiceIntent為一個Intent bindService(MediaServiceIntent,connection,BIND_AUTO_CREATE);
注意::如果點擊通知欄是從MainActivity跳轉到MainActivity,需要在配置文件的activity android:name=".MainActivity"
android:launchMode=“singleTask”,設置為單任務。
布局在源代碼包里,在Api26級以上需要使用NotificationChannel
①設置通知所觸發的PandingIntent,通過Action識別,action為自己定義的常量,setSound無聲音。通過RemoteViews去實現通知欄組件的按鈕實現
//設置通知 private void setNotification(){ String channelID="cary"; if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){ NotificationChannel channel=new NotificationChannel(channelID,"xxx",NotificationManager.IMPORTANCE_LOW); manager.createNotificationChannel(channel); } Intent intent=new Intent(MainActivity.this,MainActivity.class); PendingIntent pi=PendingIntent.getActivity(MainActivity.this,0,intent,0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notify=new Notification.Builder(MainActivity.this,channelID) .setWhen(System.currentTimeMillis()) .setSound(null) .build(); } notify.icon=android.R.drawable.btn_star; notify.contentIntent=pi; notify.contentView=remoteViews; notify.flags=Notification.FLAG_ONGOING_EVENT; remoteViews.setOnClickPendingIntent(R.id.notice,pi); //上一首 Intent prevIntent=new Intent(BUTTON_PREV_ID); PendingIntent prevPendingIntent=PendingIntent.getBroadcast(this,0,prevIntent,0); remoteViews.setOnClickPendingIntent(R.id.widget_prev,prevPendingIntent); //播放暫停 Intent playIntent=new Intent(BUTTON_PLAY_ID); PendingIntent playPendingIntent=PendingIntent.getBroadcast(this,0,playIntent,0); remoteViews.setOnClickPendingIntent(R.id.widget_play,playPendingIntent); //下一首 Intent nextIntent=new Intent(BUTTON_NEXT_ID); PendingIntent nextPendingIntent=PendingIntent.getBroadcast(this,0,nextIntent,0); remoteViews.setOnClickPendingIntent(R.id.widget_next,nextPendingIntent); //關閉 Intent closeIntent=new Intent(BUTTON_CLOSE_ID); PendingIntent closePendingIntent=PendingIntent.getBroadcast(this,0,closeIntent,0); remoteViews.setOnClickPendingIntent(R.id.widget_close,closePendingIntent); }
②動態注冊廣播
//注冊廣播 private void initButtonReceiver(){ buttonBroadcastReceiver=new ButtonBroadcastReceiver(); IntentFilter intentFilter=new IntentFilter(); intentFilter.addAction(BUTTON_PREV_ID); intentFilter.addAction(BUTTON_PLAY_ID); intentFilter.addAction(BUTTON_NEXT_ID); intentFilter.addAction(BUTTON_CLOSE_ID); registerReceiver(buttonBroadcastReceiver,intentFilter); }
③顯示廣播,需要注意的是,每次在Activity里面點擊上一首或者下一首都需要調用這個方法,刷新通知欄的標題,以及狀態專輯
//展示通知 private void showNotification(){ if(isPlaying){ remoteViews.setImageViewResource(R.id.widget_play,R.drawable.stop); }else{ remoteViews.setImageViewResource(R.id.widget_play,R.drawable.start); } remoteViews.setImageViewBitmap(R.id.widget_album,utils.getArtwork(MainActivity.this,list.get(music_index).getId(),list.get(music_index).getAlbum(),true,false)); remoteViews.setImageViewResource(R.id.widget_close,android.R.drawable.ic_menu_close_clear_cancel); remoteViews.setTextViewText(R.id.widget_title,list.get(music_index).getTitle()); remoteViews.setTextViewText(R.id.widget_artist,list.get(music_index).getArtist()); remoteViews.setTextColor(R.id.widget_title,Color.BLACK); remoteViews.setTextColor(R.id.widget_artist,Color.BLACK); notify.contentView=remoteViews; manager.notify(100,notify); }
④通知欄動作接收,使用的是內部類
public class ButtonBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String action=intent.getAction(); Log.d(TAG,"--------------------收到action:"+action+"--------------------------"); if(action.equals(BUTTON_PREV_ID)){ runOnUiThread(new Runnable() { @Override public void run() { ib_precious.performClick(); return; } }); } if(action.equals(BUTTON_PLAY_ID)){ runOnUiThread(new Runnable() { @Override public void run() { ib_state.performClick(); return; } }); } if(action.equals(BUTTON_NEXT_ID)){ runOnUiThread(new Runnable() { @Override public void run() { ib_next.performClick(); return; } }); } if(action.equals(BUTTON_CLOSE_ID)){ handler.removeCallbacks(runnable); myBinder.closeMusic(); unbindService(connection); if(remoteViews!=null){ manager.cancel(100); } unregisterReceiver(buttonBroadcastReceiver); finish(); } } }
①在AndroidManifest文件里面配置主題樣式android:theme="@style/Theme.AppCompat.Light.NoActionBar">
然后在onCreate方法里在setContentView(R.layout.activity_main);之前
設置:
if(Build.VERSION.SDK_INT>=21){ View decorView=getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); }
①在res目錄下的drawable資源下新建一個類型為selector的xml文件,里面設置屬性
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="false" android:color="#FFFFFF"/> <item android:state_selected="true" android:color="#FF7F00"/> </selector>
②在Adapter里面設置getView
currentItem == position){ holder.tv_title.setSelected(true); holder.tv_position.setSelected(true); holder.tv_duration.setSelected(true); holder.tv_artist.setSelected(true); }else{ holder.tv_title.setSelected(false); holder.tv_position.setSelected(false); holder.tv_duration.setSelected(false); holder.tv_artist.setSelected(false); }
注意:在使用的時候可能需要手動去設置里面打開權限
關于Android10.0如何實現本地音樂播放?就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。