我正在开发一个呼叫记录应用程序。它记录呼叫并将其保存在手机内存(文件管理器)中,保存音频文件后,我设法在列表视图中显示录制的文件。我想知道如何通过列表视图播放音频文件。我怎么能这样做??
答案 0 :(得分:3)
你可以像下面一样玩。
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
playSong(MEDIA_PATH + files.get(position));
}
});
这是你的playSong方法。
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
所以你的完整代码将会发布这样的东西。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.mylist);
// this will show the recorded files into ListVIew
private List<String> myList = new ArrayList<String>();
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, files);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
playSong(MEDIA_PATH + myList.get(position));
}
});
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
}
其中mp是您的媒体播放器对象private MediaPlayer mp = new MediaPlayer();
,而MEDIA_PATH是您所有录制内容的文件夹路径,
private static final String MEDIA_PATH = new String(
Environment.getExternalStorageDirectory() + "/AudioRecorder/");
答案 1 :(得分:0)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.mylist);
// this will show the recorded files into ListVIew
final String[] files = new File("mnt/sdcard/Audio File/").list();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, files);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//checking the position of item in list
Object listItem = listView.getItemAtPosition(position);
Toast.makeText(MainActivity.this, ""+listItem, Toast.LENGTH_SHORT).show();
}
});
}