Playing random sound when ImageButton is clicked on Android - java

I'm new in android and I'm trying to play random sound when ImageButton is clicked.
I'm still getting the same audio when I press the button. It should play different sounds every time the button is pressed. Also I would like to add a stop button later.
Here is my code:
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import java.util.Random;
public
class MainActivity extends AppCompatActivity {
MediaPlayer mp;
ImageButton soundbutton;
int[] sounds = {R.raw.audi, R.raw.berlin, R.raw.bratanki, R.raw.budzik, R.raw.cztery, R.raw.drzyz, R.raw.dziewczyny, R.raw.emeryt, R.raw.enter, R.raw.faza};
Random r = new Random();
int rndm = r.nextInt();
#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);
//media player
soundbutton = (ImageButton)this.findViewById(R.id.playButton);
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();
mp = MediaPlayer.create(getApplicationContext(), sounds[rndm]);
}
mp.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Thank you for your help.

You need to give a maximum to your Random. You have 10 sounds so you want a number between 0-9.
rndm = r.nextInt(10);
This will give you a number between 0-9.

Related

Android Studio Share mp3 and play/stop songs

I have this code:
import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
//Buttons
ImageButton peroperoperopero;
ImageButton personajitosdos;
peroperoperopero = (ImageButton) findViewById(R.id.peroperoperopero);
personajitosdos = (ImageButton) findViewById(R.id.personajitosdos);
//code
peroperoperopero.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp = MediaPlayer.create(MainActivity.this,R.raw.peroperopero);
mp.start();
}
});
peroperoperopero.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent compartirAudio = new Intent(android.content.Intent.ACTION_SEND);
compartirAudio.setType("audio/*");
compartirAudio.putExtra(Intent.EXTRA_STREAM,
Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/raw/" + R.raw.peroperopero));
startActivity(Intent.createChooser(compartirAudio, "Compartir vía"));
return false;
}
});
personajitosdos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp = MediaPlayer.create(MainActivity.this,R.raw.unospersonajitos);
mp.start();
}
});
}
}
I would need to know what to modify to:
Pressing the button peroperoperopero share it in WhatsApp (currently when I share it, a document is sent but not the audio)
I want only one sound to play at the same time, now if I precede the two buttons at the same time the sounds are superimposed.
I also want that while the sound is playing, if I press the button again, it stops.
please tell me what do I have to change in the code? Thank you very much.
For audio play and stop use this following:
MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
To share audio with what's app you can go to the following link
Sharing audio file

Android Java Dice roll app not changing dinamycaly

This is my MainActivity. I want when I hit "roll" button dices to "roll" - change until my cycle finish and I want to see that change. But when I run the code and hit the button I see only the end result. Tried increasing the delay of "TimeUnit", but it only slows down my app, I don't see dices "rolling". Where am I wrong and is my code in the wright direction, or am I missing something important? I am still learning Android coding :)
package com.example.rado.diceroller;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButtonListenerMethod();
}
public void myButtonListenerMethod() {
Button button = (Button) findViewById(R.id.rollButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < 3; i++) {
try {
Random rand = new Random();
int rollResult = rand.nextInt(6) + 1;
TextView diceResult = (TextView) findViewById(R.id.rollResult);
diceResult.setText(Integer.toString(rollResult));
ImageView img = (ImageView) findViewById(R.id.diceImage);
TimeUnit.MILLISECONDS.sleep(10);
switch (rollResult) {
case 1:
img.setImageResource(R.drawable.dice1);
break;
case 2:
img.setImageResource(R.drawable.dice2);
break;
case 3:
img.setImageResource(R.drawable.dice3);
break;
case 4:
img.setImageResource(R.drawable.dice4);
break;
case 5:
img.setImageResource(R.drawable.dice5);
break;
case 6:
img.setImageResource(R.drawable.dice6);
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
Your problem is that Android renders view changes after execution finish. So you can wait as many time as you want with TimeUnit.MILLISECONDS.sleep, the only result you will get will be that Android freezes himself for a bit, then restart the for loop. But he starts to render only when the execution is finished and he can say that he isn't wasting time and cpu to render something that the user will never see.
So you can't accomplish your goal in this way. You could try something like this:
package com.firegloves.test;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private int rolledTimes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButtonListenerMethod();
}
public void myButtonListenerMethod() {
Button button = (Button) findViewById(R.id.rollButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setTimeout();
}
});
}
private void setTimeout() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (rolledTimes < 6) {
// roll your dice
rollDice();
// set timeout again
setTimeout();
} else {
rolledTimes = 0;
}
}
}, 100);
}
private void rollDice() {
rolledTimes++;
Random rand = new Random();
int rollResult = rand.nextInt(6) + 1;
TextView diceResult = (TextView) findViewById(R.id.rollResult);
diceResult.setText(Integer.toString(rollResult));
ImageView img = (ImageView) findViewById(R.id.diceImage);
switch (rollResult) {
case 1:
img.setImageResource(R.drawable.dice1);
break;
case 2:
img.setImageResource(R.drawable.dice2);
break;
case 3:
img.setImageResource(R.drawable.dice3);
break;
case 4:
img.setImageResource(R.drawable.dice4);
break;
case 5:
img.setImageResource(R.drawable.dice5);
break;
case 6:
img.setImageResource(R.drawable.dice6);
break;
}
}
}

How do I transform a string from EditText to a character array, to allow audio implementation?

This is my code:
package com.example.pembroke.finalalgorhythmic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button asdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asdf = (Button) findViewById(R.id.keybutton);
asdf.setOnClickListener(MainActivity.this);
}
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
}
What I want to do, is create a character array, so that I can use media player class to play certain sounds based on the user input after my button is clicked. Any ideas?
Have you tried
notes.toCharArray() yet?
EDIT: Long version
EDIT 2: Sample implementation
MediaPlayer mp;
char[] currentNotes;
int noteIndex;
// Create the mp in onCreate and register your onCompletion callback
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
currentNotes = notes.toCharArray();
noteIndex = 0;
mp.setDataSource(getNoteResource(currentNotes[0]));
mp.start();
}
// Convert tone values into
public int getNoteResource(char tone) {…}
#Override
public void onCompletion(MediaPlayer mp) {
if(++noteIndex < currentNotes.length) {
mp.setDataSource(getNoteResource(currentNotes[noteIndex]));
mp.start();
}
}

How do I utilize a timer in Android?

I need to collect data on an interval, here the data collection is simulated with a counting integer. I can't seem to collect that integer though. I need the collection to start after a button is clicked and end when another is clicked. Any ideas?
package com.example.test.gothedistance;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
Button start, stop;
TextView sumText;
int count;
Timer t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById((R.id.stopButton));
sumText = (TextView) findViewById(R.id.sumTV);
t = new Timer();
count = 0;
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
count++;
}
},0,2000);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t.cancel();
sumText.setText(count);
}
});
}
}
The problem is likely with the line sumText.setText(count), which uses TextView.setText(int resid). That means it's looking for an id equal to count, rather than displaying the value of count. You need to convert this value to an integer first:
sumText.setText(Integer.toString(count))

How to set image resource in Android?

I am writing code for a poker game on eclipse and I am stuck on how to make the card clicked in the cardHand area show up in the playedCards area and have it removed from the deck I am drawing it from. Here's the code:
package com.viktorengineering.poker254;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import java.util.Random;
public class Poker extends Activity {
private ImageView mViewDeck;
private ImageView mViewHand;
private ImageView mViewPlayedCards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getWindow().setBackgroundDrawableResource(R.drawable.green_back);
mViewDeck = (ImageView) findViewById(R.id.deckImage);
mViewDeck.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int[] imagesArray = {R.drawable.clubs_ace, R.drawable.hearts_seven, R.drawable.diamonds_five,
R.drawable.clubs_three, R.drawable.hearts_eight, R.drawable.spades_six};
Random random = new Random();
mViewHand.setImageResource(imagesArray[new Random().nextInt(6)]);
}
});
mViewHand = (ImageView) findViewById(R.id.cardHand);
mViewHand.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mViewPlayedCards.setImageResource(0);
mViewHand.setImageResource(0);
}
});
mViewPlayedCards = (ImageView) findViewById(R.id.playedCards);
}
}
Your Image in Drawable Folder means use bellow code
mViewPlayedCards.setImageResource(R.drawable.icon);
mViewHand.setImageResource(R.drawable.icon_home);

Categories