android studio音乐播放器代码
时间: 2023-07-07 19:36:32 浏览: 101
以下是一个简单的Android Studio音乐播放器代码示例:
1. 在布局文件中添加一个播放/暂停按钮和一个文本视图:
```xml
<Button
android:id="@+id/btn_play_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"/>
<TextView
android:id="@+id/tv_current_song"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No song"/>
```
2. 在MainActivity.java中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private Button btnPlayPause;
private TextView tvCurrentSong;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(this, R.raw.song); // Replace with your own audio file
btnPlayPause = findViewById(R.id.btn_play_pause);
tvCurrentSong = findViewById(R.id.tv_current_song);
btnPlayPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btnPlayPause.setText("Play");
} else {
mediaPlayer.start();
btnPlayPause.setText("Pause");
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
btnPlayPause.setText("Play");
tvCurrentSong.setText("No song");
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.release();
mediaPlayer = null;
}
}
```
3. 运行应用程序并点击播放/暂停按钮即可播放/暂停音乐,并在文本视图中显示当前播放的歌曲名称。
阅读全文