I am triggering a MediaPlayer to play a sound on a button click.
Sometimes, the player will play the whole sound, sometimes it will
not. It always cuts off on the end. I read a few threads on here/
stackoverflow where people were having the same problem, but none of
the suggestions worked. For example, someone said that adding a
mediaPlayer.onCompletionListener() would fix the issue, but it has
not.
There were a couple posts on here about similar issues, but no real
fixes.
I can reproduce this problem on the emulator, but not my htc
incredible or my girlfriend's moto droid 2, which are both running
android 2.2.
It seems to be an issue with the 'end' parameter in setDataSource(). I
can add ~3000 bytes to end and that fixes the problem in the emulator,
but then if I run the app in my phone it cases the audio to loop back
around to the start.
Here is the code:
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.vocab_row, parent,
false);
ImageView playIcon = (ImageView) row
.findViewById(R.id.blueplay_icon);
TextView vocabWord = (TextView) row
.findViewById(R.id.vocab_text_word);
TextView vocabMeaning = (TextView) row
.findViewById(R.id.vocab_text_meaning);
vocabWord.setText(data.get(position).getKey());
vocabMeaning.setText(data.get(position).getDefinition());
final String fileName = "audio/" +
data.get(position).getAudio();
// set the click listener for the play button
playIcon.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final MediaPlayer player = new MediaPlayer();
AssetManager manager = SingleLesson.this.getAssets();
final AssetFileDescriptor descriptor;
try {
descriptor = manager.openFd(fileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
//reset player
if (player != null) {
player.reset();
}
player.setDataSource(descriptor.getFileDescriptor(),
start, end);
} catch (IOException e) {
Log.e("IO EXCEPTION: ", "while getting mp3
assets.");
e.printStackTrace();
}
// set volume
player.setVolume(100, 100);
try {
player.prepare();
} catch (IllegalStateException e) {
Log.e("ERROR: ", "media player, illegal state");
e.printStackTrace();
} catch (IOException e) {
Log.e("ERROR: ", "media player, IO exception");
e.printStackTrace();
}
player.setOnPreparedListener(new OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer inPlayer) {
player.start();
}
});
// called when the file is finished playing
player.setOnCompletionListener(new
OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer player) {
player.stop();
player.release();
}
});
}
});
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en