I am new to Android development and am working on an app that I use for my work. It required multiple buttons to each pay a sound. It is however more complicated than that.
I have managed to make a mediaplayer that will play sounds, pause, fade etc from buttons giving the button tag a string that is passed to the player as file to play. I can press other buttons and start a new sound without problems after stopping and releasing the MP. My problem is As this is for my theatre show. I want to be able to cross mix (i.e as one sound fades the next is starting). The first thought is I need a different MP for each button (which would use a lot of copy code) and also I want to be able to set up nearly 100 buttons.
Has anyone done this before, I have searched for hours online to find very little help. Any help would be useful thank you in advance.
My code is below
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnLongClickListener;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
MediaPlayer mp, mp2 ;
Button Sound1 ,Sound2, Stop, Pause , Fade;
TextView displaystatus;
String bName = "button pressed";
//set variables for volume control
private int iVolume;
private final static int INT_VOLUME_MAX = 100;
private final static int INT_VOLUME_MIN = 0;
private final static float FLOAT_VOLUME_MAX = 1;
private final static float FLOAT_VOLUME_MIN = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//connect interface to local variables
Fade=(Button)findViewById(R.id.bfade);
Sound1 = (Button)findViewById(R.id.bSound1);
Sound2 = (Button)findViewById(R.id.bSound2);
Stop =(Button)findViewById(R.id.bStop); Pause=(Button)findViewById(R.id.bPause);
displaystatus=(TextView)findViewById(R.id.tStatus);
mp2=new MediaPlayer();
//Button clicks to make play/pause/stop
Sound1.setOnClickListener(buttonPlayOnClickListener);
Sound2.setOnClickListener(buttonPlayOnClickListener);
Pause.setOnClickListener(buttonPauseOnClickListener);
Stop.setOnClickListener( buttonQuitOnClickListener);
Fade.setOnClickListener( buttonFadeOnClickListener);
//set onlongclicklistener to open SoundDetailActivity
Sound1.setOnLongClickListener(new View.OnLongClickListener(){
public boolean onLongClick(View v) {
//get the tag for the button pressed
bName= v.getTag().toString();
whenLongClick();
return true;
};
});
//set long click listener to open SoundDetailActivity
Sound2.setOnLongClickListener(new View.OnLongClickListener(){
public boolean onLongClick(View v) {
//get the tag for the button pressed
bName= v.getTag().toString();
whenLongClick();
return true;
};
});
}
private void initMediaPlayer ()
{
if(mp!=null){mp.stop();
mp.release();}
mp = new MediaPlayer();
File path=android.os.Environment.getExternalStorageDirectory();
try {
Log.v("paddy",path+bName);
mp.setDataSource(path+bName );
mp.prepare();
}catch (IOException e){
e.printStackTrace();
}
}
Button.OnClickListener buttonPlayOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View v) {
bName= v.getTag().toString();
initMediaPlayer();
Log.v("paddy",bName);
// if(mp.isPlaying()) {mp.reset();}
mp.start();
displaystatus.setText("- PLAYING -");
Pause.setText("Pause");
Log.v("paddy","no sound was playing");
}
};
Button.OnClickListener buttonPauseOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mp.isPlaying()) {
mp.pause();
displaystatus.setText("- resume -");
Pause.setText("Resume");
}else{
mp.start();
displaystatus.setText("- playing -");
Pause.setText("Pause");
}
//finish();
}
};
Button.OnClickListener buttonQuitOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
mp.reset();
displaystatus.setText("- Ready -");
}
};
public Button.OnClickListener buttonFadeOnClickListener
=new Button.OnClickListener(){
#Override
public void onClick(View v) {
fade(5000); ///time in milliseconds
// TODO Auto-generated method stub
// mp.stop();
displaystatus.setText("- Fade out -");
//finish();
}
};
public void fade(int fadeDuration)
{
//Set current volume, depending on fade or not
if (fadeDuration > 0)
iVolume = INT_VOLUME_MAX;
else
iVolume = INT_VOLUME_MIN;
updateVolume(0);
//Start increasing volume in increments
if(fadeDuration > 0)
{
final Timer timer = new Timer(true);
TimerTask timerTask = new TimerTask()
{
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
updateVolume(-1);
if (iVolume <= INT_VOLUME_MIN) {
timer.cancel();
timer.purge();
//Pause music
if (mp.isPlaying()) mp.stop();
mp.release();
mp = new MediaPlayer();
mp = MediaPlayer.create(MainActivity.this, R.raw.franksinatra);
displaystatus.setText("- Ready -");
Log.v("paddy","getting to end of fade");
}
}
});
}
};
// calculate delay, cannot be zero, set to 1 if zero
int delay = fadeDuration/INT_VOLUME_MAX;
if (delay == 0) delay = 1;
timer.schedule(timerTask, delay, delay);
}
}
// when a button is longclicked the activity sound details is opened and the sound button tag is sent as an extra.
public void whenLongClick () {
Toast.makeText(getApplicationContext(), bName , Toast.LENGTH_LONG).show();
Intent i = new Intent(this,SoundDetailActivity.class);
i.putExtra("ButtonId",bName);
startActivity(i);
}
private void updateVolume(int change)
{
//increment or decrement depending on type of fade
iVolume = iVolume + change;
//ensure iVolume within boundaries
if (iVolume < INT_VOLUME_MIN)
iVolume = INT_VOLUME_MIN;
else if (iVolume > INT_VOLUME_MAX)
iVolume = INT_VOLUME_MAX;
//convert to float value
float fVolume = 1 - ((float) Math.log(INT_VOLUME_MAX - iVolume) / (float) Math.log(INT_VOLUME_MAX));
//ensure fVolume within boundaries
if (fVolume < FLOAT_VOLUME_MIN)
fVolume = FLOAT_VOLUME_MIN;
else if (fVolume > FLOAT_VOLUME_MAX)
fVolume = FLOAT_VOLUME_MAX;
mp.setVolume(fVolume, fVolume);
}
}
Related
I wanna make "Play/Stop" button. When button "Play" is clicked, the song must be played and its text should be converted into "Stop" and when "Stop" is clicked, the button text should be changed into "Play" again and song should start again to play from the beginning.
import android.media.MediaPlayer;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button btn_playStop;
private MediaPlayer mediaPlayer;
private boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Play Music");
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.zara_sa);
btn_playStop = (Button)findViewById(R.id.btn_play_stop);
btn_playStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying() && flag==true){
stopSong();
}
else if (flag == false){
playSong();
}
}
});
}
public void playSong(){
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}
public void stopSong() {
mediaPlayer.stop();
btn_playStop.setText("Play");
flag = false;
}
}
You must call mediaPlayer.prepare(); if you called mediaPlayer.stop(); so in the first time you can just call mediaPlayer.start(); but in the next times you should call mediaPlayer.prepare(); before mediaPlayer.start();
public void playSong(){
try {
mediaPlayer.prepare();
} catch (IOException e) {
}
mediaPlayer.start();
btn_playStop.setText("Stop");
flag = true;
}
I have a sleep machine app that I want to still play the sound if the phone goes into stand by. I just edited to have the wake lock added and it is added in the manifest as well. It isnt working correctly but I am not sure why.
package com.androidsleepmachine.gamble;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class Ship extends Activity implements View.OnClickListener {
public static final Integer[] TIME_IN_MINUTES = { 30, 45, 60, 180, 360 };
public MediaPlayer mediaPlayer;
public Handler handler = new Handler();
public Button button2;
public Spinner spinner2;
private PowerManager.WakeLock wl;
// Initialize the activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(R.layout.ship);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNjfdhotDimScreen");
button2 = (Button) findViewById(R.id.btn2);
button2.setOnClickListener(this);
spinner2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,
android.R.layout.simple_spinner_item, TIME_IN_MINUTES);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter);
}
// Play the sound and start the timer
private void playSound(int resourceId) {
// Cleanup any previous sound files
cleanup();
// Create a new media player instance and start it
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
// Create the timer to stop the sound after x number of milliseconds
int selectedTime = TIME_IN_MINUTES[spinner2.getSelectedItemPosition()];
handler.postDelayed(runnable, selectedTime * 60 * 1000);
}
// Handle button callback
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn2:
playSound(R.raw.ocean_ship);
break;
}
}
protected void onStop()
{
cleanup();
super.onStop();
}
// Stop the sound and cleanup the media player
public void cleanup() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
wl.release();
}
// Cancel any previously running tasks
handler.removeCallbacks(runnable);
}
// Runnable task used by the handler to stop the sound
public Runnable runnable = new Runnable() {
public void run() {
cleanup();
}
};
}
You can make it happen with wake locks. Its part of the Powermanager api.
A detailed explanation can be found here.
i'm newbie to android programming. i have the following code but i have a problem. when i click on the seekbar without playing the sound it force close. i mean when i click the play button i can click and seek on the seekbar but without clicking the play button clicking on the seekbar will cause force close. what's the problem?!
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity implements Runnable, OnClickListener, OnSeekBarChangeListener{
private SeekBar seekBar;
private ImageButton startMedia;
private ImageButton pauseMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioControl();
}
public void AudioControl(){
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (ImageButton) findViewById(R.id.playbutton);
pauseMedia = (ImageButton) findViewById(R.id.pausebutton);
seekBar.setOnSeekBarChangeListener(this);
startMedia.setOnClickListener(this);
pauseMedia.setOnClickListener(this);
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp != null && mp.isPlaying()) return;
if(seekBar.getProgress() > 0) {
mp.start();
return;
}
mp = MediaPlayer.create(MainActivity.this, R.raw.lone);
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
if (v.equals(pauseMedia) && mp!=null) {
mp.pause();
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
}
and i have another question:
i wanna when the user clicks on play button the pause button become visible and when the user clicks on pause button it tuen invisble. what code should i wirte and please tell me where should i put this code.
Every method that manages the UI has to be called on the UI Thread itself:
You can not run
seekBar.setProgress(currentPosition);
on a Thread different frome the UIThread.
I have only been programming with Android and Java for a few weeks now, trying to make a guitar tuner to tune your guitar by ear. A simple reference tuner. I have used much of this website code to construct it.
How can I make a SoundPool stop when I click to another page/activity.
Currently I have two pages, each with 7 sound buttons. When you click any button it loops indefinitely until you click another button, then that loops and so on... If I click the button for the next page and then click a new button, the sound from the last page is still playing! rather annoying when you are trying to tune your guitar by ear!
Maybe just a simple stop button to stop the entire SoundPool would be a good idea?
Here is my SoundManager code
package org.gtdb.guitar_tuners;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class SoundManager
{
private Context pContext;
private SoundPool sndPool;
private float rate = 1.0f;
private float masterVolume = 1.0f;
private float leftVolume = 1.0f;
private float rightVolume = 1.0f;
private float balance = 0.5f;
// Constructor, setup the audio manager and store the app context
public SoundManager(Context appContext)
{
sndPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
pContext = appContext;
}
// Load up a sound and return the id
public int load(int sound_id)
{
return sndPool.load(pContext, sound_id, 1);
}
// Play a sound
public void play(int sound_id)
{
sndPool.play(sound_id, leftVolume, rightVolume, 100, -1, rate);
}
// Set volume values based on existing balance value
public void setVolume(float vol)
{
masterVolume = vol;
if(balance < 1.0f)
{
leftVolume = masterVolume;
rightVolume = masterVolume * balance;
}
else
{
rightVolume = masterVolume;
leftVolume = masterVolume * ( 2.0f - balance );
}
}
public void setSpeed(float speed)
{
rate = speed;
// Speed of zero is invalid
if(rate < 0.01f)
rate = 0.01f;
// Speed has a maximum of 2.0
if(rate > 2.0f)
rate = 2.0f;
}
public void setBalance(float balVal)
{
balance = balVal;
// Recalculate volume levels
setVolume(masterVolume);
}
// Free ALL the things!
public void unloadAll()
{
sndPool.release();
}
}
Here is my Activity code Main.java
package org.gtdb.guitar_tuners;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import android.widget.LinearLayout;
public class Main extends Activity {
SoundManager snd;
int string1, string2, string3, string4, string5, string6, string7;
OnClickListener buttZonClick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.id.adMobUnit);
// Create the adView
// Please replace MY_BANNER_UNIT_ID with your AdMob Publisher ID
AdView adView = new AdView(this, AdSize.IAB_MRECT, "aaaaaaaaaaaaa");
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
AdRequest request = new AdRequest();
request.setTesting(true);
adView.loadAd(request);
// Create an instance of our sound manger
snd = new SoundManager(getApplicationContext());
// Load the samples from res/raw
string1 = snd.load(R.raw.eadgbe1);
string2 = snd.load(R.raw.eadgbe2);
string3 = snd.load(R.raw.eadgbe3);
string4 = snd.load(R.raw.eadgbe4);
string5 = snd.load(R.raw.eadgbe5);
string6 = snd.load(R.raw.eadgbe6);
string7 = snd.load(R.raw.eadgbestrum);
/** Tuner Link **/
Button b1 = (Button) findViewById(R.id.tuner1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Main.this, Dadgad.class));
}
});
/** Tuner Link **/
Button b2 = (Button) findViewById(R.id.tuner2);
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Main.this, Daefce.class));
}
});
/** gtdb.org Link **/
ImageButton b7 = (ImageButton) findViewById(R.id.imageButton1);
b7.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri
.parse("http://www.gtdb.org/stats/click.php?id=17"));
startActivity(i);
}
});
}
public int count = 0;
// Button listener assigned in XML layout
public void clickHandler(View v) {
int id = v.getId(); // Use the button id to determine which sample
// should be played
switch (id) {
case R.id.button1:
snd.play(1);
break;
case R.id.button2:
snd.play(2);
break;
case R.id.button3:
snd.play(3);
break;
case R.id.button4:
snd.play(4);
break;
case R.id.button5:
snd.play(5);
break;
case R.id.button6:
snd.play(6);
break;
case R.id.button7:
snd.play(7);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.item1) {
Toast.makeText(Main.this,
"Android Guitar Tuner App from Guitar Tunings Database - www.gtdb.org",
Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
Apologies for the code, I might imagine that it's a mess as I am basically a newbie at Java and Android. I have been piecing together from other peoples code and from watching lynda.com videos.
The current version of my tuner is on the market but it has no loop on the sounds so you can go through the pages and listen. but without a loop on it you have to keep pressing the button to tune your guitar! you can see that here
Does Soundpool.stop(int) work for you? If so, why not just override the Activity.onPause() method and put it there?
I've literally looked everywhere on the net and found very little
clarification on how to do this.
Pretty much, I have 8 sound files laid out in an array.xml file and I
need to play a randomly chosen file ONCE per or onClick or onShake.
First off, what technique should I use to achieve this? ARRAY->RANDOM-
STRING->PLAY? RANDOM INT->PLAY? RANDOM INT->STRING->PLAY? Any kind
of direction will help greatly cause I'm almost 3 weeks worth of
research into this.
*NOTE:
MediaPlayer mp = MediaPlayer.create(JelloMan.this,
R.raw.sound)
...is what I'm stuck on being you can't replace the "R.raw" part with a string...
Here is the whole code.
package com.cyphasignals.jelloman;
import java.util.Random;
import android.app.Activity;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class JelloMan extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
private final int NUM_SOUND_FILES = 3;
//Modifier invalid here
private int mfile[] = new mfile[NUM_SOUND_FILES];
//Modifier invalid here and SECOND "mfile" is wanting to create a class
private Random rnd = new Random(3);
//Modifier invalid here
mfile[0] = R.raw.sound1;
mfile[1] = R.raw.sound2;
mfile[2] = R.raw.sound3;
int sndToPlay = rnd.nextInt(NUM_SOUND_FILES);
ShakeListener MyShake = new ShakeListener((SensorManager)
getSystemService(SENSOR_SERVICE));
MyShake.setForceThreshHold(4.0);
MyShake.setOnShakeListener(new ShakeListener.OnShakeListener() {
MediaPlayer mp = MediaPlayer.create(JelloMan.this, mfile[sndToPlay]);
//[sndToPlay] wants me to change the modifier
public void onShake() {
mp.seekTo(0);
mp.start();
}
});
ImageButton mouthbutton = (ImageButton)findViewById(R.id.billmouth);
mouthbutton.setOnClickListener(new OnClickListener() {
MediaPlayer mp = MediaPlayer.create(JelloMan.this,
mfile[sndToPlay]);
//[sndToPlay] wants me to change the modifier
public void onClick(View v) {
mp.seekTo(0);
mp.start();
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
return true;
};
return false;
}
}
In semi psuedo code:
private final int NUM_SOUND_FILES = 3;
private int mSndFiles[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random(); //import java.util.Random for this
mSndFiles[0] = R.raw.sound1;
mSndFiles[1] = R.raw.sound2;
mSndFiles[2] = R.raw.sound3;
int sndToPlay = rnd.nextInt(NUM_SOUND_FILES);
MediaPlayer mp = MediaPlayer.create(JelloMan.this, mSndFiles[sndToPlay]);
If all the sound files you have are small and you want low latency consider using SoundPool instead of MediaPlayer.
EDIT: I didn't mean for you to just copy and paste the code above into your app, i assumed you'd place things in the right places. Anyway, try this, note my comments in the code. I didn't test this and assume you also have defined the "ShakeListener" class somewhere else, but this should work.
package com.cyphasignals.jelloman;
import java.util.Random;
import android.app.Activity;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import com.cyphasignals.R;
public class JelloMan extends Activity {
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mfile[0] = R.raw.sound1; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound2; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound3;
ShakeListener MyShake = new ShakeListener((SensorManager.getSystemService(SENSOR_SERVICE));
MyShake.setForceThreshHold(4.0);
MyShake.setOnShakeListener(new ShakeListener.OnShakeListener() {
public void onShake() {
mp = MediaPlayer.create(JelloMan.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start();
}});
ImageButton mouthbutton = (ImageButton)findViewById(R.id.billmouth);
mouthbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mp = MediaPlayer.create(JelloMan.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start();
}});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
return true;
}
return false;
}
}
Structurally you need to think about how this work if someone continuously shakes the device. As it is right now it'll constantly skip back to the beginning of the sound.
well.. based on what I understood out of your question....
R.raw.sound is integer so, of course, you can't replace it with a string value..
why don't you create an int array and put each of the sound files in it...
such as below...
file[0] = R.raw.sound_0
file[1] = R.raw.sound_1
:
:
:
file[n] = R.raw.sound_n
and now, all you have to do is to get a random value between 0 to n....
MediaPlayer mp = MediaPlayer.create(JelloMan.this, file[random_value]);
Store the sounds like this:
private static final int[] SOUNDS = new int[] {
R.drawable.abort, R.drawable.aliens, R.drawable.annoying, R.drawable.better,
R.drawable.birth_control, R.drawable.bitchin, R.drawable.book_em, R.drawable.clean_up,
R.drawable.come_on, R.drawable.cry, R.drawable.damn_it, R.drawable.damn, R.drawable.game_over,
R.drawable.good, R.drawable.gotta_hurt, R.drawable.hail, R.drawable.holy_cow, R.drawable.holy_sh,
R.drawable.let_god, R.drawable.name, R.drawable.play, R.drawable.terminated,
R.drawable.this_sux, R.drawable.ugly, R.drawable.wasted, R.drawable.you_suck,
R.drawable.you_suck2, R.drawable.you_will_die
};
and you can play it:
int sndToPlay = rnd.nextInt(SOUNDS.length);
MediaPlayer mp = MediaPlayer.create(main.this, SOUNDS[sndToPlay] );
mp.seekTo(0);
mp.start();
that's work for me