• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Play several sounds

anjemalo

Lurker
Dec 1, 2013
1
0
Hello:
I need to play differents effects sounds. I have in Asset folder 50 sounds (1 second for each sound).
I don't know how to play from onclick events.
I want to pass a parameter or global variable the sound I want to play.
Can you help me, please?. Thank you
this is my code (only for two sounds in my example):

package com.example.entone;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
SoundPool sp;
int mysound=-1;
Button btnSoundChord, btnRandom;
public String Soundeff;

//-------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSoundChord=(Button)findViewById(R.id.btn);
btnSoundChord.setOnClickListener(ClickChord);

btnRandom=(Button)findViewById(R.id.btnRamdon);
btnRandom.setOnClickListener(ClickNew);

setVolumeControlStream(AudioManager.STREAM_MUSIC);
sp=new SoundPool(1,AudioManager.STREAM_MUSIC,0);

Soundeff="wind.mp3";

try{
AssetManager am = getAssets();
AssetFileDescriptor descriptor = am.openFd(Soundeff);
mysound = sp.load(descriptor,1);
}
catch (Exception e){}

}

View.OnClickListener ClickNew = new View.OnClickListener() {
public void onClick(View v) {
if (mysound != -1){
sp.play(mysound, 1, 1, 0, 0, 1); }}};

View.OnClickListener ClickChord = new View.OnClickListener() {
public void onClick(View v) {
Soundeff="bird.mp3";
if (mysound != -1){ sp.play(mysound, 1, 1, 0, 0, 1); }
}
};
}
:(
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones