Reputation: 11
I have been trying to add sound to my alphabet android application, but I don't seem to have been successful. Below is my code.
public class Sound extends Activity implements OnCompletionListener {
/** Called when the activity is first created. */
private ImageView b;
private ImageView t;
private ImageView j;
private MediaPlayer mp;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.alphabet);
b=(ImageView)findViewById(R.drawable.b);
t=(ImageView)findViewById(R.drawable.t);
j=(ImageView)findViewById(R.drawable.j);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
b();
}
});
setup();
t.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
t();
}
});
setup2();
j.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
j();
}
});
setup3();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
private void stop() {
mp.stop();
}
private void b() {
mp.stop();
loadClip();
mp.start();
b.setEnabled(true);
}
private void t() {
mp.stop();
loadClip2();
mp.start();
t.setEnabled(true);
}
private void j() {
mp.stop();
loadClip3();
mp.start();
j.setEnabled(true);
}
private void loadClip() {
try {
mp=MediaPlayer.create(this, R.raw.b);
mp.setOnCompletionListener(this);
}
catch (Throwable t) {
goBlooey(t);
}
}
private void loadClip2() {
try {
mp=MediaPlayer.create(this, R.raw.t);
mp.setOnCompletionListener(this);
}
catch (Throwable t) {
goBlooey(t);
}
}
private void loadClip3() {
try {
mp=MediaPlayer.create(this, R.raw.j);
mp.setOnCompletionListener(this);
}
catch (Throwable t) {
goBlooey(t);
}
}
private void setup() {
loadClip();
b.setEnabled(true);
}
private void setup2() {
loadClip2();
t.setEnabled(true);
}
private void setup3() {
loadClip3();
j.setEnabled(true);
}
private void goBlooey(Throwable t) {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder
.setTitle("Exception!")
.setMessage(t.toString())
.setPositiveButton("OK", null)
.show();
}
}
Would you please be so kind to take a look on my code and let me know where or what is missing. All the images are in the drawable and all clips are in the raw. Regards.
Upvotes: 0
Views: 435
Reputation: 2641
A quick skim through your code and I would say your mp doesn't exist in order to be stopping it before loading another clip on the first run.
At the top put private MediaPlayer mp=null;
then on every line where it says mp.stop(); change it to if(mp!=null) mp.stop();
Upvotes: 1