在我的Android应用程序中,我想从SD卡获取歌曲,但我无法获取该特定文件的路径。我使用的是android api level 7,它不支持以下方法。
Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_MUSIC);
我也尝试过以下代码:
path = Environment.getExternalStorageDirectory();
但我不知道如何指定音乐文件的路径。请提出一些解决方法。谢谢。
答案 0 :(得分:7)
从SD卡获取路径和歌曲名称。您可以在MediaStore中找到该歌曲的路径。
媒体提供程序包含内部和外部存储设备上所有可用媒体的元数据。
private String[] STAR = { "*" };
public void ListAllSongs()
{
Cursor cursor;
Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
if (isSdPresent()) {
cursor = getContentResolver().query(allsongsuri, STAR, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String songname = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
String albumname = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
public static boolean isSdPresent()
{
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
答案 1 :(得分:1)
你可以扫描整个SD卡的任何文件格式,这里我用于mp3和mp4 您可以将此用于您需要的任何格式。
/** To store the available media files */
private List<String> mediaList = new ArrayList<String>();
externalStoragePath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
targetDir = new File(externalStoragePath);
Log.d(" externalStoragePath ::: ", targetDir.getAbsolutePath());
public File[] mediaFiles = targetDir.listFiles();
/**
* scanFiles
*
* @param scanFiles
*/
public void scanFiles(File[] scanFiles) {
if (scanFiles != null) {
for (File file : scanFiles) {
if(mediaList.size() > 4){
return;
}
if (file.isDirectory()) {
// Log.d(" scaned File ::isDirectory: ",
// file.getAbsolutePath());
scanFiles(file.listFiles());
} else {
addToMediaList(file);
}
}
} else {
Log.d(SCANNER,
" *************** No file is available ***************");
}
}
/**
*
* @param file
*/
private void addToMediaList(File file) {
if (file != null) {
String path = file.getAbsolutePath();
int index = path.lastIndexOf(".");
String extn = path.substring(index + 1, path.length());
if (extn.equalsIgnoreCase("mp4") || extn.equalsIgnoreCase("mp3")) {// ||
Log.d(" scanned File ::: ", file.getAbsolutePath()
+ " file.getPath( ) " + file.getPath());// extn.equalsIgnoreCase("mp3"))
// {
Log.d(SCANNER, " ***** above file is added to list ");
mediaList.add(path);
}
}
}