views:

39

answers:

1

My question is a very simple one i'm sure. It's just I'm not quite sure how to effectively describe what i'm trying to achieve.

Anyway to the point, I have a simple button, I know how to "link" a raw sound file to hand make it play. BUT what i want to do is maybe link a 3 second sound to the button and just have it loop while the user holds the button, and then stops playing when the button is let go. Anyone have any example links they could share that would be great! Thank you!

edit: Thank you Cpt.Ohlund!

Thanks that was definately helpful and did the trick, however i ran into 1 more small problem maybe you could help me with I'm using a "Custom Button" as seen on http://developer.android.com/resources/tutorials/views/hello-formstuff.html

It worked fine before i added the "onTouch Listener. The Button now doesn't use it's android:state_pressed Item it just displays the normal item but not the pressed item. At least It plays the sound now. But, Any Ideas?

+1  A: 

You could use the following, just change R.raw.hit to your own soundfile:

public class XButtonSound extends Activity implements OnTouchListener {

private int sound;
private SoundPool sounds;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button donePlacing = new Button(this.getApplicationContext());
    donePlacing.setId(1);
    donePlacing.setText("Play");
    donePlacing.setOnTouchListener(this);

    this.addContentView(donePlacing, new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));


    sounds = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
    sound = sounds.load(this.getApplicationContext(), R.raw.hit, 1);
}


@Override
public boolean onTouch(View arg0, MotionEvent event) {

    switch (event.getAction() ) { 
    case MotionEvent.ACTION_DOWN: 
        System.out.println("touch");
        sounds.play(sound, 1, 1, 1, -1, 1);
        break;
    case MotionEvent.ACTION_UP:
        System.out.println("up");
        sounds.autoPause();
        break; 
    }

    return true;
}

}

Cpt.Ohlund
Thanks that was definately helpful and did the trick, however i ran into 1 small problem. I'm using a "Custom Button" as seen on http://developer.android.com/resources/tutorials/views/hello-formstuff.htmlIt worked fine before i added the "onTouch Listener. The Button now doesn't use it's android:state_pressed Item it just displays the normal item. Any Ideas?
brybam
Well that's because the onClickListener does not get invoked. Change the onTouch to return false instead of true, then the onClick(..) should also get invoked and the button will look "pressed".
Cpt.Ohlund
Really simple fix! Thanks!
brybam
hey would you know of alternative way? autoPause wasn't brought into the picture until sdk8 and I'd really like to make it 1.5 compatable I tried sounds.pause(sound); but didn't work
brybam