我创建了一个音乐播放器,它从一个androidhive教程中读取SD卡中的mp3文件 我想从原始文件夹中读取10首歌曲。
为此,我创建了这段代码 但它不起作用。
请帮忙。
package com.example.mediaplayer;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
public class SongsManager {
// SDCard Path
final String MEDIA_PATH = new String("/sdcard/");
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Constructor
public SongsManager(){
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList(){
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which are having .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
}
答案 0 :(得分:0)
这是一个支持原始文件的媒体播放器的丑陋概念验证:
public class RawMediaPlayer {
private Context mContext = null;
private int mPosition = 0;
private ArrayList<Integer> mRawList = null;
public static RawMediaPlayer create(Context context, ArrayList<Integer> rawList) {
return new RawMediaPlayer(context, rawList);
}
private RawMediaPlayer(Context context, ArrayList<Integer> rawList) {
mContext = context;
mRawList = rawList;
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mPosition++;
if (mRawList.size() <= mPosition)
return;
loadRawFile(mediaPlayer, mRawList.get(mPosition));
}
});
loadRawFile(mediaPlayer, mRawList.get(0));
}
private void loadRawFile(MediaPlayer mediaPlayer, int resId) {
try {
AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(resId);
if (afd == null)
return;
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
您可以这样使用:
final ArrayList<Integer> list = new ArrayList<Integer>();
list.add(R.raw.sample_1);
list.add(R.raw.sample_2);
list.add(R.raw.sample_3);
RawMediaPlayer.create(context, list);