import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button but1;
private Button but2;
private Button but3;
private Button but4;
private MediaPlayer mp;
private SeekBar seekBar;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.timian);
initView();
}
private void initView() {
but1 = (Button) findViewById(R.id.but1);
but2 = (Button) findViewById(R.id.but2);
but3 = (Button) findViewById(R.id.but3);
but4 = (Button) findViewById(R.id.but4);
but1.setOnClickListener(this);
but2.setOnClickListener(this);
but3.setOnClickListener(this);
but4.setOnClickListener(this);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.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) {
if (mp!= null && mp.isPlaying()){
mp.seekTo(seekBar.getProgress()); //指定到一个位置重新开始播放
}
}
});
textView = (TextView) findViewById(R.id.textView);
textView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.but1:
mp.start();
seekBar.setMax(mp.getDuration()); //设置进度条的最大长度
handler.sendEmptyMessageDelayed(0,1000);
break;
case R.id.but2:
mp.pause();
break;
case R.id.but3:
if (mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
mp = MediaPlayer.create(this,R.raw.timian);
}
break;
case R.id.but4:
mp.setLooping(true);
break;
}
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
//设置当前歌曲的总时长
int duration = mp.getCurrentPosition()/1000; //默认单位为毫秒
textView.setText(duration/60+":"+duration%60); // 除60-》分,摩60-》秒
seekBar.setProgress(mp.getCurrentPosition());
sendEmptyMessageDelayed(0,1000);
}
};
}
音乐
最新推荐文章于 2024-06-29 13:57:34 发布