Reputation: 11
Where should I add the button.playSoundEffect(SoundEffectConstants.CLICK); ? Should it be here:
//onClick event where myButton1 is pressed a click sound occurs
public void onClick(View v){
if (v.getId() == R.id.b_Press1){
myButton1.playSoundEffect(SoundEffectConstants.CLICK);
}
Upvotes: 1
Views: 566
Reputation: 152817
You don't need to call playSoundEffect()
for clicks yourself. From the docs:
The framework will play sound effects for some built in actions, such as clicking
Also note:
The sound effect will only be played if sound effects are enabled by the user
Upvotes: 0
Reputation: 1329
use this code. for more information read this link1 and link2
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
button.playSoundEffect(0);
}
});
Upvotes: 0
Reputation: 27
1) You should put mp3 file in /raw folder.
2) Put this code inside onCreate() method after setContentView()
final MediaPlayer mp = new MediaPlayer();
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
mp.reset();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("AudioFile.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
3.Sound will be played again each time you press button. You don't have to write any extra code for that.
Note that AudioFile.mp3 is the name of the mp3 file in /raw folder
Hope this answer is helpful:)
Upvotes: 1
Reputation: 800
try it out
final MediaPlayer mp = new MediaPlayer();
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
mp.reset();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("song.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Upvotes: 0
Reputation: 213
The sound effect will only be played if sound effects are enabled by the user, and isSoundEffectsEnabled() is true.
so make sure you enable it using xml like
android:soundEffectsEnabled="true"
or
through code
myButton1.setSoundEffectsEnabled(true)
Upvotes: 0