I tried searching for this in many places, but could not find an answer. I am making an app with a set of image buttons that have the alphabet on them. I want to be able to click the letter A, and hear sound file A. If I click letter B, I want to hear sound file B. So far I only have letters A and B, and sound files A and B. When I run my code, I can only hear the sound for button A, and when I press letter B, Nothing happens. This is my code:
package com.android.nishad.learn.hindi;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class AlphabetActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alphabet);
ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);
btn.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
mp = MediaPlayer.create(this, R.raw.lettera);
mp.start();
while (mp.isPlaying()) {
// do nothing
};
mp.release();
}
public void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alphabet);
ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2);
btn2.setOnClickListener(this);
}
public void onClick1(View v) {
// TODO Auto-generated method stub
mp = MediaPlayer.create(this, R.raw.letterb);
mp.start();
while (mp.isPlaying()) {
// do nothing
};
mp.release();
}
};
First, remove those
onCreate1()
andonClick1()
methods.onClick()
method is enough to receive click events for all the buttons in your layout. You can do this using theview.getId()
method. And for playing sounds I'd recommend using the SoundPool class, which has a very clear interface for such purposes. Hope this helps.Try this:
Methods
onCreate1
andonClick1
are useless as they are never invoked. Instead you should put all the initialisation code in youronCreate
method:Note however that this is a very inefficient way of handling it. Instead you should have one MediaPlayer instance and then use it to play various sounds as needed. Creating a new MediaPlayer every time a button is pressed is a waste of resources.