Android 播放音乐demo
时间: 2023-11-15 16:05:41 浏览: 224
以下是一个Android音乐播放的demo,支持本地sd卡路径下.mp3文件播放,上下歌曲切换,暂停、播放功能,手动控制进度条,支持安卓8.1+(需要apk访问sd卡权限)。具体实现可以参考以下步骤:
1.在AndroidManifest.xml文件中添加读写SD卡权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
2.在布局文件中添加音乐播放相关的控件:
```xml
<Button
android:id="@+id/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上一首" />
<Button
android:id="@+id/btn_play_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放" />
<Button
android:id="@+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一首" />
<SeekBar
android:id="@+id/seek_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
```
3.在Activity中实现音乐播放相关的逻辑:
```java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private MediaPlayer mediaPlayer;
private Button btnPrevious;
private Button btnPlayPause;
private Button btnNext;
private SeekBar seekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPrevious = findViewById(R.id.btn_previous);
btnPlayPause = findViewById(R.id.btn_play_pause);
btnNext = findViewById(R.id.btn_next);
seekBar = findViewById(R.id.seek_bar);
btnPrevious.setOnClickListener(this);
btnPlayPause.setOnClickListener(this);
btnNext.setOnClickListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
btnPlayPause.setText("播放");
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_previous:
// 上一首
break;
case R.id.btn_play_pause:
// 播放/暂停
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btnPlayPause.setText("播放");
} else {
mediaPlayer.start();
btnPlayPause.setText("暂停");
}
break;
case R.id.btn_next:
// 下一首
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.release();
}
}
```
阅读全文