Search code examples
androidaudiomedia-playerimagebutton

Android: Imagebutton, onclick play sound


I'm a noob trying to work something out and learn from it.

I have two imagebuttons and when i click them I get a kind of "schick" sound rather than the sound files that i have in the /res/raw/ directory.

This is my code:

public void button_clicked1(View v) 
{
    text1.setText("1"+width);  

     mp = MediaPlayer.create(GameScreen.this, R.raw.a);   
     mp.start();  
    }


public void button_clicked2(View v) 
{
    text1.setText("2"+height);    
     mp = MediaPlayer.create(GameScreen.this, R.raw.b);   
 mp.start();
    }

What am I doing wrong?

Thanks!

Ok, changed the above code to this:

 public void button_clicked1(View v) 
    {
        text1.setText("1"+width);  

         mp = MediaPlayer.create(GameScreen.this, R.raw.piano_a);   
             try {
                    mp .prepare();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
         mp.start();



        }


    public void button_clicked2(View v) 
    {
        text1.setText("2"+height);    
        mp = MediaPlayer.create(GameScreen.this, R.raw.piano_b);   

            try {
                mp .prepare();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
     mp.start();
        }

And it still does not work


Solution

  • EDIT: Try this:

    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    

    in your main application code. This will tell the AudioManager that when your application has focus, the volume keys should adjust music volume (found that here).

    After that, make sure that your volume is up - it may just be playing the sounds with no volume.