我在once
发生Enter
关键事件时尝试播放音频EditText
。
但媒体播放器会播放looping
音频和never stop
。并且Media Player
没有调用setOnCompletionListener
方法。
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
//Toast.makeText(LoginActivity.this, editText.getText(), Toast.LENGTH_SHORT).show();
try {
MediaPlayer mp = new MediaPlayer();
AssetFileDescriptor afd = getAssets().openFd("oxygen.ogg");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.setLooping(false);
mp.prepare();
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.i("ONComplete Media palyer", "onComplete hit");
mp.stop();
mp.release();
}
});
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
return false;
}
});
答案 0 :(得分:1)
我使用setOnSeekCompleteListener
方法代替setOnCompletionListener
。它现在播放一次并完全停止。
答案 1 :(得分:0)
将prepareAsync()
与setOnPreparedListener()
一起使用,当媒体准备好后再播放。
try {
MediaPlayer mp = new MediaPlayer();
AssetFileDescriptor afd = getAssets().openFd("oxygen.ogg");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.setLooping(false);
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.i("ONComplete Media palyer", "onComplete hit");
mp.stop();
mp.release();
}
});
} catch (Exception e) {
}