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
Related
I'm getting my feet wet on SoundPool API, I've made just a small app to learn and see how dynamic SoundPool is. But I don't know why when I load a String path (URI in String format) It simple doesn't plays!
In debug mode I realized that when I go to chose a sound using my Intent and them I load the path of the sound to the SoundPool it gives all the time a SoundID of 0. not sure if it is a problem..
Any help would be appreciated!
Code
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mKey1;
private Button mKey2;
private Button mChange;
private Button mUpload;
int mSound1;
int mSound2;
String path;
private SoundPool mSoundPool;
private boolean mSelectKey = false;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mKey1 = (Button) findViewById(R.id.key1);
mKey2 = (Button) findViewById(R.id.key2);
mChange = (Button) findViewById(R.id.Change);
mUpload = (Button) findViewById(R.id.Upload);
mKey1.setOnClickListener(this);
mKey2.setOnClickListener(this);
mChange.setOnClickListener(this);
mUpload.setOnClickListener(this);
if ( Build.VERSION.SDK_INT >= 21 ) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
mSoundPool = new SoundPool.Builder().setMaxStreams(2).setAudioAttributes(audioAttributes).build();
}else {
mSoundPool = new SoundPool(50, AudioManager.STREAM_MUSIC,0);
}
mSound1 = mSoundPool.load(this, R.raw.sound1, 1);
mSound2 = mSoundPool.load(this, R.raw.sound2, 1);
mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
Toast.makeText(MainActivity.this,"ready!",Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
path = data.getData().toString();
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.key1:
if (mSelectKey){
mSound1 = mSoundPool.load(path,1);
mSelectKey = false;
break;
}
mSoundPool.play(mSound1,1,1,1,0,1);
break;
case R.id.key2:
if (mSelectKey){
mSound2 = mSoundPool.load(path,1);
mSelectKey = false;
break;
}
mSoundPool.play(mSound2,1,1,1,0,1);
break;
case R.id.Change:
mSound1 = mSoundPool.load(this,R.raw.sound6,1);
mSound2= mSoundPool.load(this,R.raw.sound3,1);
break;
case R.id.Upload:
mSelectKey = true;
Intent uploadFile = new Intent(Intent.ACTION_GET_CONTENT);
uploadFile.setType("audio/mp3");
startActivityForResult(uploadFile,1);
break;
}
}
}
path = data.getData().toString();
First, this will return the string representation of a Uri. That will contain a scheme, such as content:. AFAIK, SoundPool load() takes a filesystem path.
Second, the Uri that you get back may not be a file, at least at a path that you can access.
Given the available flavors of load(), I would recommend that you try the one that takes an AssetFileDescriptor as input, using openAssetFileDescriptor() on a ContentResolver to get that AssetFileDescriptor, and see if you have better luck.
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);
}
}
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 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?
Me Doing "edu.sju.BlackJack" Is not causing updates that are later called to occur.
I reference the layout correctly and the calls that are supposed to update it are correct, so what do I put in for the package name?
I should add that my package name according to the manifest is the above.
This is the code I have now which currently doesn't update the screen (or i'm guessing change the value correctly).
RemoteViews name = new RemoteViews("edu.sju.BlackJack", R.layout.play_screen);
If that's not it.. would it then be this code?
name.setTextViewText(R.id.Dealer_Total, "0");
Dealer_Total is the id for the TextView that I want to change.. however again the Change is not occurring.
Thanks in advance for any and all assistance.
Here is the whole of my code that i'm talking about, first Playscreen.java
package edu.sju.BlackJack;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.*;
public class PlayScreen extends Activity implements OnClickListener {
/** Called when the activity is first created. */
GameEngine Engine = new GameEngine();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play_screen);
TextView TextDealer = (TextView)findViewById(R.id.Dealer_Total);
Engine.setView(TextDealer);
//Set up click listeners for all the buttons
View hitButton = findViewById(R.id.hit_button);
hitButton.setOnClickListener(this);
View standButton = findViewById(R.id.stand_button);
standButton.setOnClickListener(this);
//new preplay button (ML 10/24/10)
View prePlayButton = findViewById(R.id.prePlay_button);
prePlayButton.setOnClickListener(this);
Thread thread = new Thread(Engine);
thread.start();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.prePlay_button:
v.setVisibility(View.GONE);
System.out.println("Working?");
Engine.setGameStart(1);
break;
case R.id.hit_button:
Engine.gameHit(1);
break;
case R.id.stand_button:
Engine.gameStand(1);
break;
}
// More buttons go here (if any) ...
}
}
Now here's the GameEngine Thread
Not the Whole of it, just enough so you get the idea
package edu.sju.BlackJack;
import java.util.Random;
import android.widget.RemoteViews;
import android.widget.TextView;
public class GameEngine implements Runnable {
static int playerCount = 0; //keep record of which cards to change for player when hit is selected
static int dealerCount = 0; //keep record of which cards to change for dealer when dealer hits
static int win = 0; //keeps record of wins (JV 10/01/10)
static int lose = 0; //keeps record of loss (JV 10/01/10)
static int hit = 0; //let's engine know if hit button was selected (0 means it has not)
static int stand = 0; //let's engine know if stand button was selected (0 means it has not)
static int playerTotal = 0; //tells player's total (JV 10/01/10)
static int dealerTotal = 0; //tells dealer's total (JV 10/01/10)
static int playerTurn = 0; //activates buttons so that they do actions when clicked (as it's players turn)
static int startGame = 0; //starts the game when the start game button is pressed
TextView TextDealer;
RemoteViews name = new RemoteViews("edu.sju.BlackJack", R.layout.play_screen);
public void run() {
name.setTextViewText(R.id.Dealer_Total, "0");
//main();
}
public void setView(TextView a)
{
TextDealer = a;
}
public void setGameStart(int i)
{
startGame = i;
}
public void gameHit(int i)
{
if(playerTurn == 1)
hit = 1;
}
public void gameStand(int i)
{
if(playerTurn == 1)
stand = 1;
}
public void main()
{//Start Game
Deck mainDeck = new Deck();
fillDeck(mainDeck);
//TextView TextPlayer = (TextView)findViewById(R.id.Player_Total);
//TextDealer.setText("" + dealerTotal);
//TextPlayer.setText("" + playerTotal);
while(true)
{
if(startGame == 1)
{
if(mainDeck.getList().size() < 15){
mainDeck = emptyDeck();
fillDeck(mainDeck);
}
//RESET CARD VIEWS TO DEFAULT
//RESET DEALERCARD AND PLAYERCARD TOTALS TO 0
dealerTotal = 0;
playerTotal = 0;
playerCount = 0;
dealerCount = 0;
//playHand(mainDeck);
}
}
}
Whatever your problem is, I don't think it is what you think it is. If your layout is appearing in the app widget, then the package name is being handled properly. If the update (your setTextViewText() call) is not having an effect, then either R.layout.play_screen does not have R.id.Dealer_Total or you are not sending over a RemoteViews that contains the setTextViewText() instructions.