上篇文章提到了播放内存中的音乐,这次做的是播放内存中的播放器,只需要设置音源,播放准备,设置类型还有清单文件中的权限别忘了添加!
布局文件在贴一次
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/seekBar"
android:layout_weight="1" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ib_main_imageButton"
android:src="@android:drawable/ic_media_play"/>
清单文件配置
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
MainActivity主要代码
public class MainActivity extends AppCompatActivity {
private SeekBar seekBar;
private ImageButton ib_main_imageButton;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar);
ib_main_imageButton = (ImageButton) findViewById(R.id.ib_main_imageButton);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = seekBar.getProgress();
mediaPlayer.seekTo(progress);
}
});
ib_main_imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mediaPlayer == null) {
//实例化MediaPlayer
//播放内存中的音乐
//mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music);
//播放内存卡中的音乐
mediaPlayer = new MediaPlayer();
//设置音源
try {
mediaPlayer.setDataSource(getApplicationContext(), Uri.parse("file://mnt/sdcard/data/meng.mp3"));
} catch (IOException e) {
e.printStackTrace();
}
//这里要注意 需要准备一下
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//设置类型
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.start();
//把图标修改成暂停图标
ib_main_imageButton.setImageResource(android.R.drawable.ic_media_pause);
//获得音乐的时长
int duration = mediaPlayer.getDuration();
//给进度条设置最大的值
seekBar.setMax(duration);
new MyThread().start();
} else if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
//把图标修改成播放图标
ib_main_imageButton.setImageResource(android.R.drawable.ic_media_play);
} else {
mediaPlayer.start();
//把图标修改成暂停图标
ib_main_imageButton.setImageResource(android.R.drawable.ic_media_pause);
}
}
});
}
class MyThread extends Thread {
@Override
public void run() {
super.run();
while (seekBar.getProgress() <= seekBar.getMax()) {
//获取播放音乐的当前位置
int currentPosition = mediaPlayer.getCurrentPosition();
//让进度条动起来
seekBar.setProgress(currentPosition);
}
}
}
}