简体   繁体   中英

How do I implement an OnCompletionListener for this situation?

I'm trying to get two sound files to play in sequence. My app should "count" and I'd like it to use the "twenty" and "one" files instead of having an extra "twentyone" file. I'm pretty sure I need to use an OnCompletionListener for this and I've found a few previous answers that explain how to use this but I can't figure out how to implement them (I'm quite new to this as you might have guessed.)

This is the answer I think best applies to my problem.

How to play audio files one after the other

Here is my code without any attempt at implementing the OnCompletionListener .

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;


public class GameActivity extends Activity {

TextView generatedNumberTV;
EditText inputNumberET;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game_layout);

    generatedNumberTV = (TextView) findViewById(R.id.number_view);
    inputNumberET = (EditText) findViewById(R.id.number_input);

}

public void onSendGenerate(View view) {

    MediaPlayer twenty = MediaPlayer.create(GameActivity.this, R.raw.twenty);
    MediaPlayer one = MediaPlayer.create(GameActivity.this, R.raw.one);

    twenty.start();
    one.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

With this code both sound files play at the same time.

I've been stuck on this for a while now so any help would be greatly appreciated.

First you set the onCompletionListener for your MediaPlayer object:

twenty.setOnCompletionListener(listener);

And in the listener, you need to implement a method called onCompletion() which has a MediaPlayer as a parameter(which is the current MediaPlayer that is listened to by the listener).

Reference: MediaPlayer.onCompletionListener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM