How to loop using mediaplayer - Android
How do i play my audio files in sequence from my sdcard? I have two classes, one for results another for the actual rendering. Is my while loop in the correct place?
public void DoIt() {
while(!mp.isPlaying()){
AudioRenderer mr = new AudioRenderer();
mp = mr.AudioRenderer(filePath);
if(mp!=null){
mp.start();
if(!mp.isPlaying())
break;
}
}
if(mp == null){ *write results logic*}
private class AudioRenderer extends Activity {
private MediaPlayer AudioRenderer(String filePath) {
MediaPlayer mp = new MediaPlayer();
File location = new File(filePath);
Uri path = Uri.fromFile(location);
ExtentionSeperator media = new ExtentionSeperator(filePath, '.');
if(ext.equals("mp3") || ext.equals("wav")|| ext.equals("ogg")|| ext.equals("mid")||
ext.equals("flac")){
mp= MediaPlayer.create(this, path);}
return mp;}
My app just keeps writing the results without waiting for the first one to stop playing first. I want it to Render -> Play -> Wait for whole audio to stop playing -> Write result into file -> Next f开发者_如何学编程ile.
if you want them to play one after the other
there is an event in mediaplayer
mp.setOnCompletionListener()
which will fire once the first file is complete. here you can play the next file.
try this code
class MediaDemo extends Activity{
public static MediaPlayer myplayer=new MediaPlayer();
public static ArrayList<String> pathlist=new ArrayList<String>();
public void onCreate(Bundle savedInstanceState){
myplayer.reset();
myplayer.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer arg0) {
pathlist.remove(0);
if(pathlist.size()>=1){
myplayer.reset();
playAudio();
}
}
});
pathlist.add("filename");
if(!myplayer.isPlaying()){
playAudio();
}
}
public void playAudio(){
try{
if(pathlist.size()>=1){
String path=pathlist.get(0);
myplayer.setDataSource(path);
myplayer.prepare();
myplayer.start();
}
}catch(Exception e){e.printStackTrace();}
}
}
according to your code you have to use the mp.setOnCompletionListener(). In this give path for the next file which you want to play.
精彩评论