我正在从内部存储器中读取歌曲列表。我可以看到歌曲列表但是当我点击播放它时,mp.prepare会抛出一个IOException。请帮忙。如果我也从内部存储中读取,是否必须添加特定权限? -
public class MusicPlay extends ListActivity {
private static final String MEDIA_PATH = new String(
"/storage/sdcard0/Music");
private List<String> songs = new ArrayList<String>();
private MediaPlayer mp = new MediaPlayer();
private int currPos = 0;
ListView lv = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateSongList();
}
public void updateSongList() {
// TODO Auto-generated method stub
File home = new File(MEDIA_PATH);
if (home.listFiles(new Mp3Filter()).length > 0) {
for (File file : home.listFiles(new Mp3Filter())) {
songs.add(file.getName());
}
}
ArrayAdapter<String> songList = new ArrayAdapter<String>(this,
R.layout.song_item, songs);
setListAdapter(songList);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
currPos = position;
Toast.makeText(this, "Yes", 10).show();
playSong(MEDIA_PATH + songs.get(position));
}
private void playSong(String songPath) {
// TODO Auto-generated method stub
mp.reset();
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
nextSong();
}
private void nextSong() {
// TODO Auto-generated method stub
if (++currPos >= songs.size()) {
// Last song, just reset currentPosition
currPos = 0;
} else {
// Play next song
playSong(MEDIA_PATH + songs.get(currPos));
}
}
});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 0 :(得分:0)
首先我建议不要硬编码路径,使用它:
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)
|| Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED_READ_ONLY)) {
File path = manager.path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
}
代码对我来说似乎很好,我认为你的道路是错误的。或者你没有添加特权来清单。
答案 1 :(得分:0)
您错过了歌曲路径和名称之间的分隔符。将MEDIA_PATH更改为:
private static final String MEDIA_PATH = new String(
"/storage/sdcard0/Music/");
另外,我通常建议使用File,它会在使用构造函数new File (String path, String name);
时自动添加缺少的分隔符