要在Android上獲取本地音頻,您可以使用MediaStore類來訪問設備的媒體庫。以下是一個示例代碼,可獲取設備上的所有音頻文件并顯示它們的路徑:
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class AudioUtils {
public static List<String> getAllAudio(Context context) {
List<String> audioList = new ArrayList<>();
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int pathColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
do {
String audioPath = cursor.getString(pathColumn);
audioList.add(audioPath);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return audioList;
}
}
要使用上述示例,只需在您的Activity中調用getAllAudio()
方法,如下所示:
List<String> audioList = AudioUtils.getAllAudio(context);
for (String audioPath : audioList) {
Log.d("Audio", audioPath);
}
這將在Logcat中打印所有音頻文件的路徑。請注意,在使用此代碼之前,您需要在AndroidManifest.xml文件中添加適當的權限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />