简体   繁体   中英

Why doesn't my song work in my android app?

My audio doesn't play. What is the problem ??

public class AudioActivity extends AppCompatActivity {

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

        final MediaPlayer mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
        Button play = (Button) findViewById(R.id.play);
        play.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                //mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
                mp.start();
            }
        });

        Button bause = (Button) findViewById(R.id.bause);
        play.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                //mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
                mp.pause();
            }
        });
    }
}

You called setOnClickListener() on the play button twice. You meant to call bause.setOnClickListener() . When you hit the play button, instead it is pausing.

You are setting OnClickListener of play button twice. So when you click the play button it will pause the media player instead of playing it.

change it to following:

Button bause = (Button) findViewById(R.id.bause);
        bause.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                //mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);
                mp.pause();
            }
        });

This has to do with method scopes. You're creating the MediaPlayer instance inside the onCreate method. When that method ends, the mp variable goes away as well since it was created in the method's scope. When the onClickListener is executed, the variable doesn't exist anymore. Move the variable declaration to the class' scope, so that it remains available for the lifetime of the class. Something like:

public class AudioActivity extends AppCompatActivity {

  private MediaPlayer mp;

  //...

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

    mp = MediaPlayer.create(AudioActivity.this, R.raw.boot);

    //...
  }

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