Android 中 MediaPlayer简单的音乐播放
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
public class MainActivity extends AppCompatActivity {
private SeekBar sb_main_seebar;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb_main_seebar = (SeekBar) findViewById(R.id.sb_main_seebar);
//给进度条设置滑动的监听
sb_main_seebar.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);
}
});
}
public void playorstp(View view){
final ImageButton imageButton= (ImageButton) view;
if(mediaPlayer==null){
//播放内存中音频
mediaPlayer = MediaPlayer.create(this, R.raw.f);
//播放内存卡中文件
// mediaPlayer=new MediaPlayer();
//设置音源
// try {
// mediaPlayer.setDataSource(this, Uri.parse("file://com.tencent.qqmusic//f.mp3")); //内存地址
// mediaPlayer.setDataSource(this, Uri.parse("手机和电脑连接一个同一个互联网情况的IP"));列如:http://193.168.4.135/internet.mp3
//准备
// mediaPlayer.prepare();
// mediaPlayer.prepareAsync();
// } catch (Exception e) {
// e.printStackTrace();
// }
//准备完成的监听
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
//下载操作(复制)
mediaPlayer.start();
imageButton.setImageResource(android.R.drawable.ic_media_pause);
//获取音乐的总时长
int duration=mediaPlayer.getDuration();
//将进度条设置最大值为:音乐的总时长
sb_main_seebar.setMax(duration);
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_seebar.getProgress()<=sb_main_seebar.getMax()){
//获取音乐当前播放的位置
int position=mediaPlayer.getCurrentPosition();
sb_main_seebar.setProgress(position);
}
}
}
}
有什么不懂得请留言!