代码实现:
package com.example.g160628_android_27_media;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import java.io.IOException;
public class SdcardMactivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SeekBar sb_main_bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb_main_bar = (SeekBar) findViewById(R.id.sb_main_SeekBar);
//给进度条设置滑动监听
sb_main_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
//获取当前进度条的位置
int currentPosition=seekBar.getProgress();
//跳转到某个位置进行播放
mediaPlayer.seekTo(currentPosition);
}
});
}
public void playOrPause(View view){
final ImageButton imageButton= (ImageButton) view;
//实例化MediaPlayer
if(mediaPlayer==null){
//mediaPlayer = MediaPlayer.create(this, R.raw.s8);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String sdPath=Environment.getExternalStorageDirectory().getAbsolutePath();
mediaPlayer=new MediaPlayer();
//设置音频流的类型
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//设置音源
try {
//mediaPlayer.setDataSource(this, Uri.parse("file://"+sdPath+"/s1.mp3"));
mediaPlayer.setDataSource(this, Uri.parse("http://192.168.43.77:7788/s11.mp3"));
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
//设置准备监听
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
//暂停图标
imageButton.setImageResource(android.R.drawable.ic_media_pause);
//获取音乐的播放时间
int time=mediaPlayer.getDuration();
//设置进度条的最大值 为 音乐的播放时间
sb_main_bar.setMax(time);
new MyThread().start();
}
});
}
}else if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
//播放图标
imageButton.setImageResource(android.R.drawable.ic_media_play);
}else{
mediaPlayer.start();
//暂停图标
imageButton.setImageResource(android.R.drawable.ic_media_pause);
}
}
class MyThread extends Thread{
@Override
public void run() {
super.run();
while(sb_main_bar.getProgress()<sb_main_bar.getMax()){
//获取音乐当前的播放位置
int currentPosition=mediaPlayer.getCurrentPosition();
sb_main_bar.setProgress(currentPosition);
}
}
}
}