android studio mp3音乐播放器
时间: 2023-11-18 19:04:06 浏览: 225
以下是Android Studio开发的简易音乐播放器app的实现方法:
1. 在Android Studio中创建一个新项目,添加一个按钮和一个进度条控件。
2. 在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
```
3. 在MainActivity.java文件中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private boolean isPlaying = false;
private SeekBar seekBar;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mediaPlayer.seekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void playMusic(View view) {
if (!isPlaying) {
mediaPlayer = MediaPlayer.create(this, R.raw.music);
mediaPlayer.start();
isPlaying = true;
seekBar.setMax(mediaPlayer.getDuration());
updateSeekBar();
}
}
public void pauseMusic(View view) {
if (isPlaying) {
mediaPlayer.pause();
isPlaying = false;
}
}
public void stopMusic(View view) {
if (isPlaying) {
mediaPlayer.stop();
mediaPlayer.release();
isPlaying = false;
}
}
private void updateSeekBar() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
if (isPlaying) {
Runnable runnable = new Runnable() {
@Override
public void run() {
updateSeekBar();
}
};
handler.postDelayed(runnable, 1000);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (isPlaying) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
```
4. 在activity_main.xml文件中添加以下代码:
```xml
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:max="100"
android:progress="0" />
<Button
android:id="@+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:onClick="playMusic"
android:text="Play" />
<Button
android:id="@+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:onClick="pauseMusic"
android:text="Pause" />
<Button
android:id="@+id/stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:onClick="stopMusic"
android:text="Stop" />
```
5. 将音乐文件放在res/raw文件夹中。
6. 运行应用程序并测试。
阅读全文