您好,登錄后才能下訂單哦!
怎么在Android中利用SeekBar實(shí)現(xiàn)音樂播放器功能?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。
一.Demo簡(jiǎn)介
利用AIDL為Activity綁定服務(wù),利用Handler機(jī)制,發(fā)送消息更新SeekBar的UI,利用計(jì)時(shí)器定時(shí)更新SeekBar的進(jìn)度。實(shí)現(xiàn)對(duì)音樂的開始播放,到暫停,繼續(xù),以及停止播放的功能。以及實(shí)現(xiàn)拖動(dòng)進(jìn)度條播放音樂的功能。
二.AIDL接口
利用AIDL機(jī)制提供給MainActivity訪問MyMusicService的方法,實(shí)現(xiàn)播放暫停等功能。
三.主要類代碼
1.MyMusicService
package my.com.mymusicp; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.support.annotation.Nullable; import android.util.Log; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; /** * Created by c_ljf on 16-12-26. */ public class MyMusicService extends Service { private String tag="MyMusicService"; private MediaPlayer mediaPlayer; @Override public void onCreate() { super.onCreate(); mediaPlayer = new MediaPlayer(); } @Nullable @Override public IBinder onBind(Intent intent) { return new MyMusicBinder(); } class MyMusicBinder extends IMyMusicService.Stub{ @Override public void play() throws RemoteException { playmusic(); } @Override public void pause() throws RemoteException { pausemusic(); } @Override public void stop() throws RemoteException { stopmusic(); } @Override public void continuePlay() throws RemoteException { rePlayMusic(); } @Override public void seekPlayProgress(int position) throws RemoteException { seekPlayPositiom(position); } } //播放音樂 public void playmusic(){ mediaPlayer.reset(); String url = "sdcard/Music/Fade.mp3"; Log.i(tag,url); try { mediaPlayer.setDataSource(url); mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } // might take long! (for buffering, etc) mediaPlayer.start(); //更新播放進(jìn)度條 seekPlayProgress(); } public void pausemusic(){ mediaPlayer.pause(); Log.i(tag,"暫停播放"); } public void stopmusic(){ mediaPlayer.reset(); Log.i(tag,"停止播放"); mediaPlayer.stop(); } @Override public void onDestroy() { super.onDestroy(); } public void seekPlayPositiom(int positon){ Log.i(tag,"設(shè)置播放位置"); mediaPlayer.seekTo(positon); } public void seekPlayProgress(){ /*1.獲取當(dāng)前歌曲的總時(shí)長(zhǎng)*/ final int duration=mediaPlayer.getDuration(); //計(jì)時(shí)器對(duì)象 final Timer timer=new Timer(); final TimerTask task=new TimerTask() { @Override public void run() { //開啟線程定時(shí)獲取當(dāng)前播放進(jìn)度 int currentposition=mediaPlayer.getCurrentPosition(); //利用message給主線程發(fā)消息更新seekbar進(jìn)度 Message ms=Message.obtain(); Bundle bundle=new Bundle(); bundle.putInt("duration",duration); Log.i(tag,"歌曲總長(zhǎng)度"+duration); bundle.putInt("currentposition",currentposition); Log.i(tag,"當(dāng)前長(zhǎng)度"+currentposition); //設(shè)置發(fā)送的消息內(nèi)容 ms.setData(bundle); //發(fā)送消息 MainActivity.handler.sendMessage(ms); } }; timer.schedule(task,300,500); //當(dāng)播放結(jié)束時(shí)停止播放 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Log.i(tag,"取消計(jì)時(shí)任務(wù)"); timer.cancel(); task.cancel(); } }); } public void rePlayMusic() { Log.i(tag, "繼續(xù)播放音樂"); mediaPlayer.start(); } }
2.Mainactivity
package my.com.mymusicp; import android.Manifest; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.SeekBar; public class MainActivity extends AppCompatActivity { private IMyMusicService iMyMusicService; private static SeekBar seekBar; private Button btpause_play; private boolean b=true;//判斷暫停和繼續(xù)播放 public static Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { //處理消息 Bundle bundle=msg.getData(); //獲取歌曲長(zhǎng)度和當(dāng)前播放位置,并設(shè)置到進(jìn)度條上 int duration=bundle.getInt("duration"); int currentposition=bundle.getInt("currentposition"); seekBar.setMax(duration); seekBar.setProgress(currentposition); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); verifyStoragePermissions(MainActivity.this); //獲取播放暫停按鈕 btpause_play=(Button) findViewById(R.id.bt_pause); Intent intent=new Intent(MainActivity.this,MyMusicService.class); bindService(intent,new MyConn(),BIND_AUTO_CREATE); seekBar=(SeekBar) findViewById(R.id.seekBar); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { try { iMyMusicService.seekPlayProgress(seekBar.getProgress()); } catch (RemoteException e) { e.printStackTrace(); } } }); } //定義服務(wù)連接類 class MyConn implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { iMyMusicService=IMyMusicService.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } } public void play(View v){ try { iMyMusicService.play(); } catch (RemoteException e) { e.printStackTrace(); } } public void pause(View v){ try { if(b) { iMyMusicService.pause(); b=false; btpause_play.setText("繼續(xù)播放"); } else{ b=true; iMyMusicService.continuePlay(); btpause_play.setText("暫停播放"); } } catch (RemoteException e) { e.printStackTrace(); } } public void stop(View v){ try { iMyMusicService.stop(); } catch (RemoteException e) { e.printStackTrace(); } } // Storage Permissions private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, }; /** * Checks if the app has permission to write to device storage * * If the app does not has permission then the user will be prompted to grant permissions * * @param activity */ public static void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } } }
四.布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="my.com.mymusicp.MainActivity"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:id="@+id/linearLayout"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="開始播放" android:onClick="play" android:id="@+id/bt_start"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="暫停播放" android:layout_weight="1" android:onClick="pause" android:id="@+id/bt_pause"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="停止播放" android:onClick="stop" android:id="@+id/bt_stop"/> </LinearLayout> <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/seekBar" android:layout_below="@+id/linearLayout" android:layout_alignParentLeft="true" android:layout_alignParentStart="true"/> </RelativeLayout>
五.注冊(cè)服務(wù)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.com.mymusicp"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <service android:name=".MyMusicService"/> </application> </manifest>
關(guān)于怎么在Android中利用SeekBar實(shí)現(xiàn)音樂播放器功能問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。