一、MediaPlayer类
1、常用方法
方法名称 | 功能 |
setDataSource() | 设置要播放的音频文件 |
prepare() | 在开始播放前。调用该方法准备播放 |
start() | 开始播放或者继续播放音频 |
pause() | 暂停播放 |
reset() | 重置MediaPlayer对象 |
seekTo() | 从指定位置播放 |
stop() | 停止播放,调用后MediaPlayer无法再播放音频 |
release() | 释放与MediaPlayer对象相关资源 |
isPlaying() | 判断当前是否在播放状态 |
getDuration() | 获取载入音频的文件时长 |
2、实例化MediaPlayer对象
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STERAM_MUSIC); // 设置音频类型
setAudioStreamType()方法设置音频类型,常用的音频有:
1、AudioManager.STREAM_MUSIC 音乐
2、AudioManager.STREAM_RING 响铃
3、AudioManager.STREAM_NOTIFICTION 提示音
4、AudioManager.STREAM_ALARM 闹钟
3、设置数据源
1、播放应用自带的音频文件
mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.XXX);
2、播放sd卡里面的音频
mediaPlayer.setDataSource("音频在SD卡路径");
3、播放网络音频
mediaPlayer.setDataSource("http://www.xxx.mp3"); // 注意申请网络权限
MediaPlayer 例子:
MainActivity:
package com.example.music;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static SeekBar sb;
private static TextView tv_progress,tv_total;
private ObjectAnimator mAnimator;
private MusicService.MusicControl mMusicControl;
MyServiceConn conn;
Intent mIntent;
private int position=0;
private boolean isUnbind = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
tv_progress = findViewById(R.id.tv_progress);
sb = findViewById(R.id.sb);
tv_total = findViewById(R.id.tv_total);
findViewById(R.id.btn_next).setOnClickListener(this);
findViewById(R.id.btn_before).setOnClickListener(this);
findViewById(R.id.btn_pause).setOnClickListener(this);
findViewById(R.id.btn_continue_play).setOnClickListener(this);
findViewById(R.id.btn_play).setOnClickListener(this);
mIntent = new Intent(this, MusicService.class);
conn = new MyServiceConn();
bindService(mIntent,conn,BIND_AUTO_CREATE);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == seekBar.getMax()){
// mAnimator.pause()
++position;
int p = position % 6;
mMusicControl.setPosition(p);
mMusicControl.changeMusic();
}
}
// 滑动条开始滑动时调用
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
// 滑动条停止滑动时调用
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = seekBar.getProgress();
mMusicControl.seekTo(progress);
mMusicControl.continuePlay();
mAnimator.start();
}
});
ImageView iv_music = findViewById(R.id.iv_music);
mAnimator = ObjectAnimator.ofFloat(iv_music,"rotation",0f,360.0f);
mAnimator.setDuration(10000); // 动画旋转一周的时间为10秒
mAnimator.setInterpolator(new LinearInterpolator());
mAnimator.setRepeatCount(-1);
}
public static Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
int duration = bundle.getInt("duration");
int currentPosition = bundle.getInt("currentPosition");
sb.setMax(duration);
sb.setProgress(currentPosition);
int minute = duration / 1000 / 60;
int second = duration/1000%60;
System.out.println(second +" "+minute);
String strMinute =null;
String strSecond = null;
if(minute<10){
strMinute ="0"+minute;
}else {
strMinute = minute+"";
}
if (second<10){
strSecond ="0"+second;
}else {
strSecond = second +"";
}
tv_total.setText(strMinute+":"+strSecond);
minute = currentPosition/1000/60;
second = currentPosition/1000%60;
if(minute<10){
strMinute ="0"+minute;
}else {
strMinute = minute+"";
}
if (second<10){
strSecond ="0"+second;
}else {
strSecond = second +"";
}
tv_progress.setText(strMinute+":"+strSecond);
}
};
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_play:
mMusicControl.play();
mAnimator.start();
break;
case R.id.btn_continue_play:
mMusicControl.continuePlay();
break;
case R.id.btn_next:
// unbind(isUnbind);
// isUnbind = true;
// finish();
++position;
int p = position % 6;
mMusicControl.setPosition(p);
mMusicControl.changeMusic();
break;
case R.id.btn_pause:
mMusicControl.pausePlay();
mAnimator.pause();
break;
case R.id.btn_before:
if (position!=0){
--position;
int ps = position %5;
mMusicControl.setPosition(ps);
}else {
mMusicControl.setPosition(5);
position = 5;
}
mMusicControl.changeMusic();
break;
}
}
class MyServiceConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mMusicControl = (MusicService.MusicControl) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
private void unbind(boolean isUnbind){
if (!isUnbind){
mMusicControl.pausePlay();
unbindService(conn);
stopService(mIntent);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbind(isUnbind);
}
}
Service:
package com.example.music;
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 MusicService extends Service {
private MediaPlayer mPlayer;
private Timer mTimer;
public MusicService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new MusicControl();
}
@Override
public void onCreate() {
super.onCreate();
mPlayer = new MediaPlayer();
}
public void addTimer(){
if (mTimer == null){
mTimer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
if (mPlayer == null)
return;
int duration = mPlayer.getDuration(); // 获取歌曲总时长
// 获取当前播放进度
int currentPosition = mPlayer.getCurrentPosition();
try {
// 创建消息对象
Message msg = MainActivity.handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt("duration",duration);
bundle.putInt("currentPosition",currentPosition);
msg.setData(bundle);
MainActivity.handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
};
mTimer.schedule(task,5,500);
}
}
class MusicControl extends Binder{
private int position = 0;
private int musics[] = {R.raw.paris,R.raw.closer,R.raw.something_just_like_this,R.raw.mu,R.raw.see_you_again,R.raw.gu};
public void play(){
try{
mPlayer.reset();
mPlayer = MediaPlayer.create(getApplicationContext(),musics[position]);
mPlayer.start();
addTimer();
}catch (Exception e){
e.printStackTrace();
}
}
public void pausePlay(){
mPlayer.pause();
}
public void continuePlay(){
mPlayer.start();
}
public void seekTo(int progress){
mPlayer.seekTo(progress);
}
public void changeMusic(){
mPlayer.reset();
mPlayer = MediaPlayer.create(getApplicationContext(),musics[position]);
mPlayer.start();
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mPlayer == null) return;
if (mPlayer.isPlaying()) mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/img_1"
>
<ImageView
android:id="@+id/iv_music"
android:layout_width="240dp"
android:layout_height="240dp"
android:layout_gravity="center_horizontal"
android:layout_margin="15dp"
android:src="@drawable/img" />
<SeekBar
android:id="@+id/sb"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingRight="8dp"
android:paddingLeft="8dp">
<TextView
android:id="@+id/tv_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
/>
<TextView
android:id="@+id/tv_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="00:00"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_play"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@drawable/btn_bg_selector"
android:text="播放音乐"
/>
<Button
android:id="@+id/btn_pause"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@drawable/btn_bg_selector"
android:text="暂停播放"
/>
<Button
android:id="@+id/btn_continue_play"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@drawable/btn_bg_selector"
android:text="继续播放"
/>
<Button
android:id="@+id/btn_next"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@drawable/btn_bg_selector"
android:text="下一首"
/>
<Button
android:id="@+id/btn_before"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@drawable/btn_bg_selector"
android:text="上一首"
/>
</LinearLayout>
</LinearLayout>