Android - Play Random Sounds on Button Click - android

i am very new in "coding" for Googles Android.
At the moment i am programming a small app with one button. If you click on it, it plays a random sound. BUT :D ... it plays a sound, on every start an other. But no random sounds if you press the button often.
I dont know where is my mistake.
Here is the code (don't laugh!):
public class MainActivity extends Activity {
//MediaPlayer
MediaPlayer mp;
ImageButton soundbutton;
//Sounds
int[] sounds={R.raw.s1, R.raw.s2, R.raw.s3, R.raw.s4, R.raw.s5, R.raw.s6, R.raw.s7, R.raw.s8, R.raw.s9, R.raw.s10};
Random r = new Random();
int Low = 0;
int High = 10;
int rndm = r.nextInt(High-Low) + Low;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
//MediaPlayer
soundbutton = (ImageButton)this.findViewById(R.id.randomsoundbutton89);
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
soundbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
}
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Help! (from Germany)!

Use this code to get different sound
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
//MediaPlayer
soundbutton = (ImageButton)this.findViewById(R.id.randomsoundbutton89);
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
soundbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
rndm = r.nextInt(High-Low) + Low;
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
}
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

Related

How to make ImageButton repeat a sound each time it's clicked

I am trying to get the Image Button to play a sound each time it's clicked. For example, if the sound is playing for few seconds and I press the button again it should start from the beginning. I managed to get the sound working but it's not repeating it. How can I get it to start over?
ImageButton bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (ImageButton) findViewById(R.id.clickme);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bird);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
}
Try this:
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.bird);
}
mp.start();
} catch(Exception e) {
e.printStackTrace();
}
}
Use MediaPlayer.seekto() to seek to the start of the audio file.
ImageButton bt;
private MediaPlayer mp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (ImageButton) findViewById(R.id.clickme);
mp = MediaPlayer.create(this, R.raw.bird);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()) {
mp.seekTo(0);
} else {
mp.start();
}
}
});
}

MediaPlayer does not work properly

I'm using MediaPlayer for play a click sound when user clicks on a button. Sometimes the sound will play fine but other times it is too slow. For example first click is fine but second click is too slow.
Here is my code:
private MediaPlayer mClickSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mClickSound = MediaPlayer.create(this, R.raw.click);
}
#Override
public void onClick(View view) {
try {
if (mClickSound.isPlaying()) {
mClickSound.stop();
mClickSound.release();
mClickSound = MediaPlayer.create(this, R.raw.click);
}
mClickSound.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Try this:
mClickSound.reset();
AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.click);
if (afd == null) return;
mClickSound.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mClickSound.start();
afd.close();
setDataSource is taken from here:
https://stackoverflow.com/a/20111291/6159609
The reset method is supposed to be faster.
Please try below code working fine for me...
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
Button btn;
MediaPlayer mClickSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
mClickSound = MediaPlayer.create(this, R.raw.click);
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickSound.isPlaying()) {
mClickSound.reset();
}
else {
mClickSound = MediaPlayer.create(this, R.raw.click);
mClickSound.start();
}
}
}

Android is hanging when I press button to play music in second time

I used these codes from this reference. They want to click on button to play music and then click again to stop playing. (in their comment they said it was worked for them but hanging for me)
It is work just for first time. I mean for first click the music is playing. for second click the music is stop but for third click the phone emulator show this error:
unfortunately your program has stopped.
This is my code:
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btnRain);
//mp = MediaPlayer.create(this, R.raw.rain);
mp = MediaPlayer.create(MainActivity.this, R.raw.rain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
//MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);
// mp.start();
public void onClick(View v) {
if (mp.isPlaying()) {
mp.stop();
mp.release();
}
else {
mp.start();
}
}
});
}
In onCreate initialize mp as :
mp = new MediaPlayer();
The error is you are releasing the media player object mp, which destroys the object, call reset method instead of release.
if (mp.isPlaying())
{
mp.stop();
mp.reset();
}
else {
mp = MediaPlayer.create(LegalActivity.this, R.raw.free1);
mp.start();
}
use this below code for play and pause the music:
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btnRain);
//mp = MediaPlayer.create(this, R.raw.rain);
mp = MediaPlayer.create(MainActivity.this, R.raw.rain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
//MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);
// mp.start();
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
}
else {
mp.start();
}
}
});
}
This is an AUDIO activity that works fine and it allows you to upload songs with a spinner.
public class AUDIO extends Activity{
Spinner spCanciones;
Button btnRep,btnGra,btnParar;
File audios;
String cancionSelec;
String arquivoGravar;
private MediaPlayer mediaplayer;
private boolean pause;
private MediaRecorder mediaRecorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
spCanciones=(Spinner)findViewById(R.id.spCanciones);
btnGra=(Button)findViewById(R.id.btnGra);
btnParar=(Button)findViewById(R.id.btnParar);
btnRep=(Button)findViewById(R.id.btnRep);
mediaplayer=new MediaPlayer();
enlazarSpinner();
//REPRODUCIR
btnRep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reproducir();
}
});
//PARAR
btnParar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaplayer.isPlaying())
mediaplayer.stop();
pause=false;
}
});
//GRABAR
btnGra.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
grabarAudio();
}
});
}
public void enlazarSpinner(){
final ArrayList<String>songs=new ArrayList<>();
audios=new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/AUDIO/");
String [] play=audios.list();
for (int i=0;i<play.length;i++)songs.add(play[i]);
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, songs);
// Opcional: layout usuado para representar os datos no Spinner
adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Enlace do adaptador co Spinner do Layout.
spCanciones.setAdapter(adaptador);
// Escoitador
spCanciones.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
cancionSelec = songs.get(pos);
Log.i("Cancion", cancionSelec);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}); // Fin da clase anónima
}
public void reproducir(){
try {
mediaplayer.reset();
mediaplayer.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath()+"/AUDIO/"+cancionSelec);
mediaplayer.prepare();
mediaplayer.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("MULTIMEDIA",e.getMessage());
}
}
public void grabarAudio(){
String timeStamp = DateFormat.getDateTimeInstance().format(
new Date()).replaceAll(":", "").replaceAll("/", "_")
.replaceAll(" ", "_");
mediaRecorder = new MediaRecorder();
arquivoGravar = Environment.getExternalStorageDirectory().getAbsolutePath()+"/AUDIO/"+ timeStamp + ".3gp";
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setMaxDuration(10000);
mediaRecorder.setAudioEncodingBitRate(32768);
mediaRecorder.setAudioSamplingRate(8000); // No emulador só 8000 coma
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setOutputFile(arquivoGravar);
try {
mediaRecorder.prepare();
} catch (Exception e) {
// TODO Auto-generated catch block
mediaRecorder.reset();
}
mediaRecorder.start();
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setMessage("GRAVANDO").setPositiveButton(
"PREME PARA PARAR",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
});
dialog.show();
enlazarSpinner();
}
#Override
protected void onPause() {
super.onPause();
if (mediaplayer.isPlaying()){
mediaplayer.pause();
pause = true;
}
}
#Override
protected void onResume() {
super.onResume();
if (pause) {
mediaplayer.start();
pause = false;
}
}
#Override
protected void onSaveInstanceState(Bundle estado) {
estado.putBoolean("MEDIAPLAYER_PAUSE", pause);
super.onSaveInstanceState(estado);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.putBoolean("MEDIAPLAYER_PAUSE", false);
pause = savedInstanceState.getBoolean("MEDIAPLAYER_PAUSE");
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaplayer.isPlaying()) mediaplayer.stop();
if (mediaplayer != null) mediaplayer.release();
mediaplayer = null;
}
}

Is this a good way to use MediaPlayer?

I think this is a decent way to use MediaPlayer for a Button or one time use. Am I right? Is the try block necessary? And what should I be trying to catch here? I'm really having a hard time finding a rock solid way to play a sound once.
// Button sound
private void playButtonSound() {
try{
final MediaPlayer startPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.sound);
startPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
startPlayer.release();
}
});
startPlayer.start();
} catch(Throwable t){}
}
I use it like that:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.tosse);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}

Issue with looping an audio file

How can i get the value of repetitions completed from mp.setLooping(true). I can use OnCompletionListener to get number of repetitions, but it produces 1sec delay between looping, which is annoying in a music oriented app. OnCompletionListener looping is not smooth asmp.setLooping(true).
Any suggestions ? Thank in advance.
Code with 1sec delay or gap between looping:
public class MainActivity extends Activity {
MediaPlayer mp1;
Button play;
int maxCount=10,n=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button) findViewById(R.id.button1);
mp = MediaPlayer.create(MainActivity.this, R.raw.soundfile);
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mpplay();
}
});
}
private void mpplay() {
mp1.start();
mp1.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp1) {
if (n <= maxCount) {
mp1.start();
n++;
if (n >= maxCount) {
n = 1;
mp1.stop();
}
}
}
});
}}
Try this out:
MediaPlayer mp1;
double play_times = 10;
int sound_length;
Handler handler;
boolean sound_playing = false;
int times_played = 0;
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.home);
handler = new Handler();
mp1 = MediaPlayer.create(this, R.raw.soundfile);
sound_length = mp1.getDuration();
mpplay();
}
private void mpplay() {
times_played = 0;
mp1.setLooping(true);
mp1.start();
sound_playing = true;
handler.postDelayed(loop_stopper, (int)(sound_length*(play_times-.5)));
handler.postDelayed(counter, sound_length);
}
private Runnable loop_stopper = new Runnable() {
public void run() {
sound_playing = false;
mp1.setLooping(false);
}
};
private Runnable counter = new Runnable() {
public void run() {
if (sound_playing) {
times_played++;
handler.postDelayed(counter, sound_length);
}
}
};
handler.postDelayed(loop_stopper, (int)(sound_length*(play_times-.5)));
This line will stop the looping halfway through the last desired loop. Since this just means it won't continue looping, the sound file will still be fully played on the last repeat.

Categories

Resources