Android音乐播放器——甩动切歌
前言: 使用MediaPlayer实现Android的音乐播放器,能够播放、暂停、停止歌曲,控制播放上一首,下一首歌曲;同时可以使用感应器来感应甩动动作,然后完成切换歌曲的操作。
1. 第一步
布局文件activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/previous_ib"
android:src="@mipmap/previous_track"
android:background="@null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton
android:id="@+id/play_ib"
android:src="@mipmap/bofang"
android:background="@null"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton
android:id="@+id/pause_ib"
android:src="@mipmap/pause"
android:background="@null"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton
android:id="@+id/stop_ib"
android:src="@mipmap/stop"
android:background="@null"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton
android:id="@+id/next_ib"
android:src="@mipmap/next_track"
android:background="@null"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:gravity="bottom|right"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/volume_plus_ib"
android:src="@mipmap/volume_increase"
android:background="@null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton
android:id="@+id/volume_decrease_ib"
android:src="@mipmap/volume_decrease"
android:background="@null"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
布局文件里添加了一写控制音乐的组件,包括播放、暂停、停止、上一首、下一首、音量加、音量减的按钮。
2. 第二步
编写甩动手机时的监听器,ShakeListener.java
public class ShakeListener implements SensorEventListener {
//速度阈值,当摇晃速度达到这值后产生作用
private static final int SPEED_SHRESHOLD = 4000;
//两次检测的时间间隔
private static final int UPTATE_INTERVAL_TIME = 70;
//传感器管理器
private SensorManager sensorManager;
//传感器
private Sensor sensor;
//重力感应监听器
private OnShakeListener onShakeListener;
//上下文
private Context context;
//手机上一个位置时重力感应坐标
private float lastX;
private float lastY;
private float lastZ;
//上次检测时间
private long lastUpdateTime;
//构造器
public ShakeListener(Context c) {
//获得监听对象
context = c;
start();
}
//开始
public void start() {
//获得传感器管理器
sensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
if(sensorManager != null) {
//获得重力传感器
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
//注册
if(sensor != null) {
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
}
}
//停止检测
public void stop() {
sensorManager.unregisterListener(this);
}
//设置重力感应监听器
public void setOnShakeListener(OnShakeListener listener) {
onShakeListener = listener;
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
//现在检测时间
long currentUpdateTime = System.currentTimeMillis();
//两次检测的时间间隔
long timeInterval = currentUpdateTime - lastUpdateTime;
//判断是否达到了检测时间间隔
if(timeInterval < UPTATE_INTERVAL_TIME)
return;
//现在的时间变成last时间
lastUpdateTime = currentUpdateTime;
//获得x,y,z坐标
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
//获得x,y,z的变化值
float deltaX = x - lastX;
float deltaY = y - lastY;
float deltaZ = z - lastZ;
//将现在的坐标变成last坐标
lastX = x;
lastY = y;
lastZ = z;
double speed = Math.sqrt(deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ)/timeInterval * 10000;
//达到速度阀值,发出提示
if(speed >= SPEED_SHRESHOLD)
onShakeListener.onShake();
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
//摇晃监听接口
public interface OnShakeListener {
public void onShake();
}
3. 编写Activity——Music2Activity.java
public class Music2Activity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener {
private ImageButton play,pause,stop,volume_plus,volume_decrease,next,previous;
private MediaPlayer mediaPlayer = new MediaPlayer();
private AudioManager audioManager;
int maxVolume,currentVolume;
String[] musicList = new String[]{"/sdcard/music1.mp3",
"/sdcard/music2.mp3","/sdcard/music3.mp3","/sdcard/music4.mp3"};
int currentMusic = 0;
private ShakeListener shakeListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music2);
audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
initView();
play.setOnClickListener(Music2Activity.this);
pause.setOnClickListener(Music2Activity.this);
stop.setOnClickListener(Music2Activity.this);
volume_plus.setOnClickListener(Music2Activity.this);
volume_decrease.setOnClickListener(Music2Activity.this);
next.setOnClickListener(Music2Activity.this);
previous.setOnClickListener(Music2Activity.this);
//监听器,自动播放下一首歌曲
mediaPlayer.setOnCompletionListener(Music2Activity.this);
if (ContextCompat.checkSelfPermission(Music2Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Music2Activity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}else {
initMediaPlayer();//初始化mediaplayer
}
shakeListener = new ShakeListener(Music2Activity.this);
shakeListener.setOnShakeListener(new ShakeListener.OnShakeListener() {
@Override
public void onShake() {
//对手机摇晃后的处理(如换歌曲,换图片……)
currentMusic++;
if (currentMusic == musicList.length){
currentMusic = 0;
}
changeMusic();
}
});
}
private void initView() {
play = (ImageButton) findViewById(R.id.play_ib);
pause = (ImageButton) findViewById(R.id.pause_ib);
stop = (ImageButton) findViewById(R.id.stop_ib);
volume_plus = (ImageButton) findViewById(R.id.volume_plus_ib);
volume_decrease = (ImageButton) findViewById(R.id.volume_decrease_ib);
next = (ImageButton) findViewById(R.id.next_ib);
previous = (ImageButton) findViewById(R.id.previous_ib);
}
private void initMediaPlayer() {
try {
mediaPlayer.setDataSource(musicList[0]);//指定音频文件的路径
mediaPlayer.prepare();//让mediaplayer进入准备状态
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initMediaPlayer();
} else {
Toast.makeText(Music2Activity.this,"denied access",Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_ib:
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();//开始播放
}
break;
case R.id.pause_ib:
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();//暂停播放
}
break;
case R.id.stop_ib:
Toast.makeText(Music2Activity.this,"停止播放",Toast.LENGTH_SHORT).show();
if (mediaPlayer.isPlaying()) {
mediaPlayer.reset();//停止播放
initMediaPlayer();
}
break;
//音量加
case R.id.volume_plus_ib:
maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,AudioManager.FLAG_SHOW_UI);
currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Toast.makeText(Music2Activity.this,"音量增加,最大音量是:" + maxVolume + ",当前音量" + currentVolume,
Toast.LENGTH_SHORT).show();
break;
//音量减
case R.id.volume_decrease_ib:
maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,AudioManager.FLAG_SHOW_UI);
currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Toast.makeText(Music2Activity.this,"音量减小,最大音量是:" + maxVolume + ",当前音量" + currentVolume,
Toast.LENGTH_SHORT).show();
break;
//下一首
case R.id.next_ib:
currentMusic++;
if (currentMusic == musicList.length){
currentMusic = 0;
}
changeMusic();
Toast.makeText(Music2Activity.this,"下一首:"+musicList[currentMusic],Toast.LENGTH_SHORT).show();
break;
//上一首
case R.id.previous_ib:
currentMusic--;
if (currentMusic == -1) {
currentMusic = musicList.length-1;
}
changeMusic();
Toast.makeText(Music2Activity.this,"上一首:"+musicList[currentMusic],Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
private void changeMusic() {
//重置
mediaPlayer.reset();
try {
//设置音乐文件来源
mediaPlayer.setDataSource(musicList[currentMusic]);
//准备(缓冲文件)
mediaPlayer.prepare();
//播放开始
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
currentMusic++;
if (currentMusic == musicList.length){
currentMusic = 0;
}
changeMusic();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
前言: 这样我们就可以通过甩动手机来完成切换歌曲的任务了。
转载自原文链接, 如需删除请联系管理员。
原文链接:Android音乐播放器——甩动切歌,转载请注明来源!