我的應用程序的資產目錄中有多個音頻文件。當用戶點擊一個按鈕時,我想按照一定的順序播放這些文件,一個接一個地播放。音頻文件之間不應該有明顯的延遲。實現這一目標的最佳方法是什麼?如何播放一個接一個的音頻文件
我正在考慮使用MediaPlayer
對象和OnCompletionListener
s。但是,這意味着我必須創建很多OnCompletionListener
,因爲我需要知道每次下一個音頻文件。我錯過了什麼,或者有更好的方法嗎?
我的應用程序的資產目錄中有多個音頻文件。當用戶點擊一個按鈕時,我想按照一定的順序播放這些文件,一個接一個地播放。音頻文件之間不應該有明顯的延遲。實現這一目標的最佳方法是什麼?如何播放一個接一個的音頻文件
我正在考慮使用MediaPlayer
對象和OnCompletionListener
s。但是,這意味着我必須創建很多OnCompletionListener
,因爲我需要知道每次下一個音頻文件。我錯過了什麼,或者有更好的方法嗎?
你是對的,不需要很多OnCompletionListener's。
//define a variable to be used as index.
int audioindex = 0;
//Extract the files into an array
String[] files = null;
files = assetManager.list("audiofiles");
然後在你的OnCompletionListener中。
mp.setOnCompletionListener(new OnCompletionListener(){
// @Override
public void onCompletion(MediaPlayer arg0) {
// File has ended, play the next one.
FunctionPlayFile(files[audioindex]);
audioindex+=1; //increment the index to get the next audiofile
}
});
檢查這一點,這些類可播放MP3的網址一個又一個,我創造了他們大約在某些時候,並且可以調整從資產打........
創建資源目錄的原始文件夾,並把在那裏,你的聲音文件
現在...使用PlayMedia像這樣
int[] soundIDs = {R.raw.yes, R.raw.eat};
PlayMedia playAudio = new PlayMedia(context,soundIDs);
playAudio.execute();
,並定義PlayMedia類像這個
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.util.Log;
public class PlayMedia extends AsyncTask<Void, Void, Void> {
private static final String LOG_TAG = PlayMedia.class.getSimpleName();
Context context;
private MediaPlayer mediaPlayer;
int[] soundIDs;
int idx =1;
public PlayMedia(MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
}
public PlayMedia(final Context context, final int[] soundIDs) {
this.context = context;
this.soundIDs=soundIDs;
mediaPlayer = MediaPlayer.create(context,soundIDs[0]);
setNextMediaForMediaPlayer(mediaPlayer);
}
public void setNextMediaForMediaPlayer(MediaPlayer player){
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if(soundIDs.length>idx){
mp.release();
mp = MediaPlayer.create(context,soundIDs[idx]);
setNextMediaForMediaPlayer(mp);
mp.start();
idx+=1;
}
}
});
}
@Override
protected Void doInBackground(Void... params) {
try {
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "", e);
} catch (SecurityException e) {
Log.e(LOG_TAG, "", e);
} catch (IllegalStateException e) {
Log.e(LOG_TAG, "", e);
}
return null;
}
}
我嘗試過,但後4-5秒的音頻突然停止......你知道這是爲什麼發生? – 2015-10-12 09:52:35
好的答案.... – vnshetty 2011-08-16 04:07:09