音乐播放器及各种功能
public class Main2Activity extends AppCompatActivity {
private Button btn;
private MediaPlayer player;
private Button stop;
private Button puase;
private Button restart;
private SeekBar sb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
btn = (Button) findViewById(R.id.btn);
stop = (Button) findViewById(R.id.stop);
restart = (Button) findViewById(R.id.restart);
sb = (SeekBar) findViewById(R.id.sb);
restart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
player.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(player.isPlaying()){
player.stop();
}
}
});
puase = (Button) findViewById(R.id.puase);
puase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(player.isPlaying()){
player.pause();
}
}
});
player = new MediaPlayer();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
player.reset();
player.setDataSource("http://www.ytmp3.cn/down/43210.mp3");
// player.prepare();
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
sb.setMax(player.getDuration());
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
player.seekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
sb.setProgress(player.getCurrentPosition());
}
},0,1000);
}
}