我在播放列表视图中的歌曲时遇到问题。
歌曲正确保存,但我不能播放它们。我有一首歌的路径,所以一切都应该有用......
这是oncreate和outside的代码:
listView = (ListView) findViewById(R.id.filesList);
ArrayList<String> FilesInFolder = GetFiles("/sdcard/Kandydaci");
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
File audioFile = getApplicationContext().getCacheDir();
String name = (String) parent.getItemAtPosition(position);
String OUTPUT_FILE ="sdcard/Kandydaci/"+name;
mediaPlayer.setDataSource(OUTPUT_FILE);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
这是bug,我点击listview中的项目后得到:
E/ExtMediaPlayer-JNI: env->IsInstanceOf fails
E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
E/ExtMediaPlayer-JNI: env->IsInstanceOf fails
E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
E/FileSource: Failed to open file 'sdcard/Kandydaci/Thu Nov 30 17:36:34 GMT+01:00 2017.mp3'. (Permission denied)
E/GenericSource: Failed to create data source!
E/MediaPlayer: error (1, -2147483648)
答案 0 :(得分:0)
您的代码绝对正确,但问题是您错过了定义访问EXTERNAL STORAGE的权限。
就这样。
在清单中声明:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
现在在列表设置之前添加此代码:
If(ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission))
{
//This is called if user has denied the permission before
//In this case I am just asking the permission again
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
else
{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
}
else {
Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
}
通过此代码,您将获得存储访问权限,此处权限为:
String ="Manifest.permission.WRITE_EXTERNAL_STORAGE";
快乐的编码!!