android音乐播放
时间: 2023-06-30 08:21:40 浏览: 56
在 Android 平台上,我们可以使用 MediaPlayer 类来实现音乐播放。以下是一个简单的示例:
1. 在布局文件中添加一个 Button 和一个 TextView,用于选择和显示音乐文件的路径。
```xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/select_music_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Music"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/music_path_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No music selected"
android:layout_below="@id/select_music_button"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
```
2. 在 Activity 中获取 Button 和 TextView 的引用,并为 Button 添加点击事件。点击 Button 后会弹出文件选择器,选择一个音乐文件后会将其路径显示在 TextView 中。
```java
public class MainActivity extends AppCompatActivity {
private Button selectMusicButton;
private TextView musicPathTextview;
private String musicFilePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectMusicButton = findViewById(R.id.select_music_button);
musicPathTextview = findViewById(R.id.music_path_textview);
selectMusicButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivityForResult(intent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri uri = data.getData();
musicFilePath = uri.getPath();
musicPathTextview.setText(musicFilePath);
}
}
}
```
3. 在 Activity 中添加一个方法用于初始化 MediaPlayer,将音乐文件路径作为参数传入。
```java
private MediaPlayer mediaPlayer;
private void initMediaPlayer(String filePath) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
```
4. 在 Activity 的 onResume 方法中调用 initMediaPlayer 方法来初始化 MediaPlayer。
```java
@Override
protected void onResume() {
super.onResume();
if (musicFilePath != null) {
initMediaPlayer(musicFilePath);
}
}
```
5. 在 Activity 的 onPause 方法中调用 MediaPlayer 的 release 方法来释放资源。
```java
@Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
```
6. 在 Activity 中添加一个方法用于播放音乐。
```java
private void playMusic() {
if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
```
7. 在 Activity 中添加一个方法用于暂停音乐。
```java
private void pauseMusic() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
```
现在我们已经完成了音乐播放器的基本功能,可以通过调用 playMusic 和 pauseMusic 方法来控制音乐的播放和暂停。