make click sound when pressing a button - android

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);
}

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:)

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)

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();
}
}
});

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);
}
});

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

Related

How to play audio on button click (recycler view)

How do I play an audio from raw folder on button click? Here, I'm using recyclerview to show the list of audios. But when click play, it doesn't play any sound.
private Button btnPlay;
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = new MediaPlayer();
try{
mp.setDataSource(ss.getSoundURI());
mp.prepare();
mp.start();
} catch (Exception e){
e.printStackTrace();
}
}
});
You can use this function:
public void playSound(final String fileName) {
MediaPlayer mpPlayer = null;
try {
int fileId = getResources().getIdentifier(fileName, "raw", getPackageName());
mpPlayer = MediaPlayer.create(this, fileId);
mpPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mpPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} catch (Exception e) {
e.printStackTrace();
if (mpPlayer != null)
mpPlayer.release();
}
}
NOTE: use file name without file extension. for example if your file name is file1.wav you should send file1 as a file name to function NOT file1.wav .
NOTE: In first line I defined the mpPlayer and initialize it because i want to use it in the catch block.

Android Media Player Replay Option

How can i replay a .mp3 in my app? I can't replay the mp3 using the start method
Here is the code segment :
mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.splashsound);
mMediaPlayer.setLooping(true);
Button myButtonOne = (Button) findViewById(R.id.songon);
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mMediaPlayer.start();
}
});
Button myButtonTwo = (Button) findViewById(R.id.songoff);
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mMediaPlayer.isPlaying()){
//mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
});
Can anyone please tell me what i am doing wrong here?
If you want to replay the mp3 why do release and set to null your media player?
I guess that is your problem!
Just stop and start it again without releasing your media player instance.
To replay mp3 track try this:
private void playSong(int songIndex) {
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Or without calling reset():
mediaPlayer.setLooping(true);

Play a sound from res/raw

I m making an app which is supposed to play a few sounds with the mediaPlayer.
This is the code i use :
String[] name = {"sonar_slow","sonar_medium","sonar_fast"};
String link = "/res/raw/" + name[state-1] + ".mp3";
try {
player.setDataSource(link);
player.prepare();
player.start();
} catch(Exception e) {
e.printStackTrace();
}
I also tried this :
if(state==1){
player.create(this, R.raw.sonar_slow);
}else if(state==2){
player.create(this, R.raw.sonar_medium);
}else if(state==3){
player.create(this, R.raw.sonar_fast);
}
player.start();
But none of the above is working. My app is not crashing but the sound is not playing.
Any ideas ?
There are two problems.
Problem 1
You cannot reference resources inside your projects /res/raw directory in this fashion. The file "/res/raw/sonar_slow.mp3" in your project directory is not stored in "/res/raw/sonar_slow.mp3" in your apk. Instead of the following:
MediaPlayer mp = MediaPlayer.create(this);
mp.setSource("sonar_slow");
You need to use
MediaPlayer mp = MediaPlayer.create(this, R.raw.sonar_slow);
Problem 2
The following is wrong: it calls a static method that does not modify the player.
player.create(this, R.raw.sonar_slow);
You should instead call
player = MediaPlayer.create(this, R.raw.sonar_slow);
Full solution
Below is a reusable AudioPlayer class that encapsulates MediaPlayer. This is slightly modified from "Android Programming: The Big Nerd Ranch Guide". It makes sure to remember to clean up resources
package com.example.hellomoon;
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer {
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public void play(Context c, int rid) {
stop();
mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
}
How to play a file with MediaPlayer:
MediaPlayer mp = MediaPlayer.create(this, R.raw.mysound); // sound is inside res/raw/mysound
mp.start();
This is a simple example of how to play a sound with the Android MediaPlayer.
You have two buttons hat each play a different sound. The selecting of the sound and actually playing it is done in the manageSound() method. The sounds "hello", "goodbye" and "what" are in the res/raw directory:
MediaPlayer mp = null;
String hello = "Hello!";
String goodbye = "GoodBye!";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button buttonHello = (Button) findViewById(R.id.idHello);
buttonHello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
managerOfSound(hello);
} // END onClick()
}); // END buttonHello
final Button buttonGoodBye = (Button) findViewById(R.id.idGoodBye);
buttonGoodBye.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
managerOfSound(goodbye);
} // END onClick()
}); // END buttonGoodBye
} // END onCreate()
protected void manageSound(String theText) {
if (mp != null) {
mp.reset();
mp.release();
}
if (theText.equals(hello))
mp = MediaPlayer.create(this, R.raw.hello);
else if (theText.equals(goodbye))
mp = MediaPlayer.create(this, R.raw.goodbye);
else
mp = MediaPlayer.create(this, R.raw.what);
mp.start();
}
Taken from here: http://www.badprog.com/android-mediaplayer-example-of-playing-sounds
Furthermore, I would strongly recommend using SoundPool instead of MediaPlayer, for better Performance and usability.
http://developer.android.com/reference/android/media/SoundPool.html
Please also check if your sound is muted - I know this sounds stupid, but it happens to the best of us ;)
You need to do it like this :
try{
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
Make sure your only playing when the file has finished preparing.

Any way to speed up this code. Streaming audio Android

Making an app and streaming audio from site. I've got a menu and when I click the button to open the radio activity it can take from 8-20 seconds to load and sometimes force closes. Any help would be awesome thanks.
Code:
public class Radio extends Activity {
private MediaPlayer mp;
private ImageButton pauseicon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
getActionBar().setDisplayHomeAsUpEnabled(true);
/**
* Play button click event plays a song and changes button to pause
* image pauses a song and changes button to play image
* */
String res = "http://216.235.91.36/play?s=magic24point7&d=LIVE365&r=0&membername=&session=magic24point7:0&AuthType=NORMAL&app_id=live365%3ABROWSER&SaneID=24.79.96.172-13316781890137014897763&tag=live365";
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if (mp.isPlaying()) {
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if (mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
if (mp != null) {
if (mp.isPlaying())
mp.stop();
mp.release();
}
// there is no reason to call super.finish(); here
// call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
Use prepareAsync() and setOnPreparedListener() instead of prepare(). prepare() blocks the UI thread until it returns and is not recommended for a stream. This may be the cause your crash.
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(res);
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
mp.start();
}
});
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
http://developer.android.com/reference/android/media/MediaPlayer.html#prepare()
Prepares the player for playback, synchronously. After setting the datasource and the display surface, you need to either call prepare() or prepareAsync(). For files, it is OK to call prepare(), which blocks until MediaPlayer is ready for playback.
Otherwise I think the network is your bottleneck. The fastest way to speed things up is to ensure your server/client communication is quick. There doesn't seem to be anything inherently slow about your code.

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
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.

Categories

Resources