溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

android實(shí)現(xiàn)音樂播放器

發(fā)布時(shí)間:2020-10-11 10:51:35 來源:腳本之家 閱讀:181 作者:ITzhongzi 欄目:移動(dòng)開發(fā)

需求描述: 擁有播放,暫停,重新播放和停止等功能。 并且隨著音樂的進(jìn)度,進(jìn)圖條會(huì)自動(dòng)更新。手動(dòng)拖動(dòng)進(jìn)度條也會(huì)更新音樂的進(jìn)度。

效果展示

android實(shí)現(xiàn)音樂播放器

示例代碼

MainActivity

package com.example.www.musicdemo;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

 private Iservice mIservice;
 private static SeekBar mSeekBar;

 public static Handler mHandler = new Handler() {
 @Override
 public void handleMessage(Message msg) {
  //獲取我們攜帶的數(shù)據(jù)
  Bundle data = msg.getData();
  //獲取歌曲的總時(shí)長(zhǎng) 和 當(dāng)前進(jìn)度
  int duration = data.getInt("duration");
  int currentPosition = data.getInt("currentPosition");

  mSeekBar.setMax(duration);
  mSeekBar.setProgress(currentPosition);
 }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
// requestPermissions(new String[]{Manifest.permission.INTERNET}, 100);

 mSeekBar = (SeekBar) findViewById(R.id.seekBar);

 Intent intent = new Intent(this, MyService.class);
 startService(intent);

 bindService(intent, conn, BIND_AUTO_CREATE);
 // 設(shè)置seekbar的拖動(dòng)時(shí)間監(jiān)聽
 mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
  @Override
  public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  mIservice.callSeekTo(seekBar.getProgress());
  }

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {

  }

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {

  }
 });

 }

 public void playmusic(View view) {
 mIservice.callPlayMusic();
 }

 public void onPause(View view) {
 mIservice.callPauseMusic();
 }

 public void stopMusci(View view) {
 mIservice.stopMusic();
 }

 public void replaymusic(View view) {
 mIservice.callRePlayMusic();
 }



 ServiceConnection conn = new ServiceConnection() {

 @Override
 public void onServiceConnected(ComponentName name, IBinder service) {
  mIservice = (Iservice) service;
 }

 @Override
 public void onServiceDisconnected(ComponentName name) {

 }
 };

 @Override
 protected void onDestroy() {
 unbindService(conn);
 super.onDestroy();
 }
}

MyService

package com.example.www.musicdemo;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service {

 private MediaPlayer mMp;

 public MyService() {
 }

 @Override
 public IBinder onBind(Intent intent) {
 // TODO: Return the communication channel to the service.

 return new MyBinder();
 }

 @Override
 public void onCreate() {
 mMp = new MediaPlayer();

 super.onCreate();
 }

 @Override
 public void onDestroy() {
 super.onDestroy();
 }

 public void playMusic(){
 try {

  mMp.setDataSource("/resource/n1/77/39/2163816420.mp3");
  mMp.prepare();
  mMp.start();
  updateSeekBar();
 } catch (Exception e) {
  e.printStackTrace();
 }

 }

 public void pauseMusic(){
 mMp.pause();
 }

 public void stopMusic(){
 mMp.stop();
 }

 public void updateSeekBar(){
 final int duration = mMp.getDuration();
 final Timer timer = new Timer();
 final TimerTask timerTask = new TimerTask() {
  @Override
  public void run() {
  int currentPosition = mMp.getCurrentPosition();

  Message msg = Message.obtain();
  Bundle bundle = new Bundle(); // map
  bundle.putInt("duration", duration);
  bundle.putInt("currentPosition", currentPosition);

  msg.setData(bundle);
  MainActivity.mHandler.sendMessage(msg);
  }
 };

 timer.schedule(timerTask, 100, 1000);
 // 監(jiān)聽音樂播放完畢
 mMp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  @Override
  public void onCompletion(MediaPlayer mp) {
  System.out.println("歌曲播放完成了");
  timer.cancel();
  timerTask.cancel();
  }
 });

 }

 //實(shí)現(xiàn)指定播放的位置
 public void seekTo(int position){
 mMp.seekTo(position);
 }


 private class MyBinder extends Binder implements Iservice{

 @Override
 public void callPlayMusic() {
  playMusic();
 }

 @Override
 public void callPauseMusic() {
  pauseMusic();
 }

 @Override
 public void callRePlayMusic() {
  mMp.start();
 }

 @Override
 public void stopMusic() {
  MyService.this.stopMusic();
 }

 @Override
 public void callSeekTo(int position) {

  seekTo(position);
 }

 }
}

Iservice

package com.example.www.musicdemo;

/**
 * @author Administrator
 * @name mutilMedia
 * @class name:com.example.www.musicdemo
 * @class describe
 * @time 2019/4/8 11:23
 * @change
 * @chang time
 * @class describe
 */
public interface Iservice {
 //把想暴露的方法都定義在接口中
 public void callPlayMusic();
 public void callPauseMusic();
 public void callRePlayMusic();
 public void stopMusic();
 public void callSeekTo(int position);
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">

 <Button
 android:id="@+id/button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginStart="8dp"
 android:layout_marginTop="8dp"
 android:onClick="playmusic"
 android:text="播放"
 app:layout_constraintEnd_toStartOf="@+id/button2"
 app:layout_constraintHorizontal_bias="0.5"
 app:layout_constraintStart_toStartOf="parent"
 app:layout_constraintTop_toTopOf="parent" />

 <Button
 android:id="@+id/button2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="暫停"
 app:layout_constraintEnd_toStartOf="@+id/button3"
 app:layout_constraintHorizontal_bias="0.5"
 app:layout_constraintStart_toEndOf="@+id/button"
 app:layout_constraintTop_toTopOf="@+id/button"
 android:onClick="onPause"/>

 <Button
 android:id="@+id/button3"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="重新播放"
 app:layout_constraintEnd_toStartOf="@+id/button4"
 app:layout_constraintHorizontal_bias="0.5"
 app:layout_constraintStart_toEndOf="@+id/button2"
 app:layout_constraintTop_toTopOf="@+id/button2"
 android:onClick="replaymusic"/>

 <Button
 android:id="@+id/button4"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="停止播放"
 app:layout_constraintEnd_toEndOf="parent"
 app:layout_constraintHorizontal_bias="0.5"
 app:layout_constraintStart_toEndOf="@+id/button3"
 app:layout_constraintTop_toTopOf="@+id/button3"
 android:onClick="stopMusci"/>

 <SeekBar
 android:id="@+id/seekBar"
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_marginStart="8dp"
 android:layout_marginTop="32dp"
 android:layout_marginEnd="8dp"
 app:layout_constraintEnd_toEndOf="parent"
 app:layout_constraintHorizontal_bias="1.0"
 app:layout_constraintStart_toStartOf="parent"
 app:layout_constraintTop_toBottomOf="@+id/button2" />

</android.support.constraint.ConstraintLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.www.musicdemo">

 <uses-permission android:name="android.permission.INTERNET" />

 <application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:roundIcon="@mipmap/ic_launcher_round"
 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=".MyService"
  android:enabled="true"
  android:exported="true"></service>
 </application>

</manifest>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(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)容。

AI