阅读量:2
要在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" />