安卓开发:实现带SeekBar的媒体播放器歌曲控制
这是文章《带有SeekBar的安卓媒体播放器的歌曲》的第1部分(共2部分)。
在本教程中,我们将使用MediaPlayer类在我们的Android应用程序中实现一个基本的音频播放器。我们将添加一个播放/停止功能,并允许用户通过SeekBar来改变歌曲的位置。
安卓媒体播放器MediaPlayer类用于播放音频和视频文件。我们将使用MediaPlayer类的常见方法:
- start()
- stop()
- release() – 防止内存泄漏。
- seekTo(position) – 将与SeekBar一起使用
- isPlaying() – 让我们知道歌曲是否正在播放。
- getDuration() – 用于获取总时长。使用这个方法我们将知道SeekBar的上限。此函数返回以毫秒为单位的时长。
- setDataSource(FileDescriptor fd) – 用于设置要播放的文件。
- setVolume(float leftVolume, float rightVolume) – 用于设置音量级别。值是0到1之间的浮点数。
我们将播放存储在Android Studio项目的assets文件夹中的mp3文件。从Assets文件夹中获取声音资产文件。
AssetFileDescriptor descriptor = getAssets().openFd("filename");
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
为了创建一个可以播放音频并可以修改当前音乐曲目位置的应用程序,我们需要实现三件事:
- MediaPlayer
- 带文本的SeekBar – 在滑块旁边显示当前进度时间。
- 可运行线程 – 用于更新SeekBar。
项目结构
在你的 build.gradle 文件中添加以下依赖项。
implementation 'com.android.support:design:28.0.0-alpha3'
编码
这是文章《带有SeekBar的安卓媒体播放器的歌曲》的第2部分(共2部分)。
以下是activity_main.xml的代码。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:layout_margin="16dp"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="播放/停止歌曲。\n使用SeekBar拖动进度"
android:textStyle="bold" />
<SeekBar
android:id="@+id/seekbar"
android:layout_margin="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:src="@android:drawable/ic_media_play"
android:text="播放音频" />
</LinearLayout>
我们已经添加了一个浮动操作按钮(FloatingActionButton),点击时会播放或停止音频。MainActivity.java类的代码如下所示:
package com.Olivia.androidmediaplayersong;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements Runnable {
MediaPlayer mediaPlayer = new MediaPlayer();
SeekBar seekBar;
boolean wasPlaying = false;
FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fab = findViewById(R.id.button);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
playSong();
}
});
final TextView seekBarHint = findViewById(R.id.textView);
seekBar = findViewById(R.id.seekbar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekBarHint.setVisibility(View.VISIBLE);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
seekBarHint.setVisibility(View.VISIBLE);
int x = (int) Math.ceil(progress / 1000f);
if (x < 10)
seekBarHint.setText("0:0" + x);
else
seekBarHint.setText("0:" + x);
if (x > 0 && mediaPlayer != null && !mediaPlayer.isPlaying()) {
clearMediaPlayer();
fab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, android.R.drawable.ic_media_play));
MainActivity.this.seekBar.setProgress(0);
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(seekBar.getProgress());
}
}
});
}
public void playSong() {
try {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
clearMediaPlayer();
seekBar.setProgress(0);
wasPlaying = true;
fab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, android.R.drawable.ic_media_play));
}
if (!wasPlaying) {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
}
fab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, android.R.drawable.ic_media_pause));
AssetFileDescriptor descriptor = getAssets().openFd("suits.mp3");
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mediaPlayer.prepare();
mediaPlayer.setVolume(0.5f, 0.5f);
mediaPlayer.setLooping(false);
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
new Thread(this).start();
}
wasPlaying = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
int currentPosition = mediaPlayer.getCurrentPosition();
int total = mediaPlayer.getDuration();
while (mediaPlayer != null && mediaPlayer.isPlaying() && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
clearMediaPlayer();
}
private void clearMediaPlayer() {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
在上面的代码中,点击浮动操作按钮(FloatingActionButton)后,playSong函数会被触发。在该函数中,我们会停止歌曲并重置MediaPlayer和浮动操作按钮的图标,每隔一秒执行一次。一旦调用了mediaPlayer.prepare()方法,歌曲的详细信息就会可用。我们现在可以获取持续时间,并将其设置为SeekBar的最大位置。将setLooping设置为false可以避免歌曲无限循环播放,直到用户手动停止。我们启动一个线程来触发已实现的Runnable接口的run方法。在run方法中,我们每秒更新一次进度,这会触发SeekBar监听器的onProgressChanged方法。在监听器中,我们将TextView的偏移量设置为SeekBar的滑块下方。我们通过将毫秒转换为秒来设置时间显示。当用户移动SeekBar时,会触发相同的方法。当用户停止拖动SeekBar时,会触发onStopTrackingTouch方法,在该方法中,我们使用seekTo方法更新MediaPlayer实例上的歌曲位置。一旦歌曲播放完成,我们将SeekBar的位置更新为初始位置,并清除MediaPlayer实例。没有音频的应用程序输出如下所示:教程到此结束。您可以从下面的链接下载项目并播放歌曲。
安卓媒体播放器歌曲示例
GitHub项目链接。