android studio Koala简单的音乐播放器
时间: 2025-01-03 15:35:47 浏览: 5
### 创建 Android 音乐播放器应用
#### 准备工作
为了构建一个简单的音乐播放器,在开始编码之前,需确保已安装并配置好最新版的 Android Studio 和必要的 SDK 工具。
#### 添加权限声明
在 `AndroidManifest.xml` 文件中添加读取存储卡上的音频文件所需权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
```
#### 布局设计
定义主活动布局文件 `activity_main.xml` 如下所示:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- 显示当前歌曲名称 -->
<TextView
android:id="@+id/songTitleLabel"
android:textColor="#000"
android:textSize="24sp"
android:gravity="center_horizontal"
android:paddingTop="24dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<!-- 控制按钮区域 -->
<Button
android:id="@+id/playBtn"
android:text="Play"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
```
#### 主要逻辑实现
编辑 MainActivity.java 或者 Kotlin 版本的 MainActivity.kt 来处理媒体控制逻辑。这里给出 Java 实现的例子:
```java
package com.example.musicplayer;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore;
import android.database.Cursor;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
private MediaPlayer mediaPlayer;
private TextView songTitleLabel;
private Button playBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化组件引用
songTitleLabel = findViewById(R.id.songTitleLabel);
playBtn = findViewById(R.id.playBtn);
requestStoragePermission();
setupMediaPlayerControls();
}
private void setupMediaPlayerControls() {
playBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
togglePlayback();
}
});
}
private void togglePlayback() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
pauseMusic();
} else {
startPlayingFirstSong();
}
}
private void startPlayingFirstSong() {
ArrayList<String> songsList = getSongsFromDevice();
if (!songsList.isEmpty()){
String firstSongPath = songsList.get(0); // 获取第一个音轨路径
try{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(firstSongPath);
mediaPlayer.prepare();
mediaPlayer.start();
updateUIForPlayingState(songsList.get(0));
} catch(Exception e){
e.printStackTrace();
}
setOnCompletionListener();
}
}
private void setOnCompletionListener(){
mediaPlayer.setOnCompletionListener(new OnCompletionListener(){[^1]
@Override
public void onCompletion(MediaPlayer mp) {
stopMedia(mp);
updateUIForStoppedState();
}
});
}
private void updateUIForPlayingState(String title){
playBtn.setText("Pause");
songTitleLabel.setText(title);
}
private void updateUIForStoppedState(){
playBtn.setText("Play");
songTitleLabel.setText("");
}
private void pauseMusic(){
if(mediaPlayer!=null){
mediaPlayer.pause();
updateUIForPausedState();
}
}
private void updateUIForPausedState(){
playBtn.setText("Resume");
}
private void stopMedia(MediaPlayer mPlayer){
if(mPlayer!=null){
mPlayer.stop();
mPlayer.release();
mPlayer=null;
}
}
private ArrayList<String> getSongsFromDevice(){
final ArrayList<String> tempAudioList=new ArrayList<>();
Uri uri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor=getContentResolver().query(uri,null,null,null,
MediaStore.Audio.AudioColumns.DISPLAY_NAME+" ASC");
if(cursor!=null&&cursor.moveToFirst()){
do{
int audioIndex=cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
tempAudioList.add(cursor.getString(audioIndex));
}while (cursor.moveToNext());
cursor.close();
}
return tempAudioList;
}
@AfterPermissionGranted(REQUEST_CODE_ASK_PERMISSIONS)
private void requestStoragePermission(){
String[] perms={Manifest.permission.READ_EXTERNAL_STORAGE};
if(EasyPermissions.hasPermissions(this,perms)){
// Already have permission, do the thing!
}else{
// Do not have permissions, request them now
EasyPermissions.requestPermissions(this,"Need to read storage", REQUEST_CODE_ASK_PERMISSIONS, perms);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults){
super.
阅读全文