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.
Related
I am fairly new to android studio and developing with android. I have been trying this for months now, I need to record and save a video using Google Glass. The code that I currently have follows. This is code inspired from https://developers.google.com/glass/develop/gdk/camera#images
When I run this process, the video will start recording and then when the recording is stopped, it will give me the option "tap to accept" When I tap, nothing happens. I understand this is because my method "processVideoWhenReady" does absolutely nothing.
I would like to know if anyone could help me with what I should include in that method to save the video and allow it to be viewed by the user within my application.
Any literature or websites that have useful information about developing for Google Glass would also be a huge help if possible. Google's documentation doesn't seem very helpful to me and very limited.
import android.app.Activity;
import android.graphics.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.content.Intent;
import android.os.FileObserver;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.VideoView;
import com.google.android.glass.content.Intents;
import com.google.android.glass.widget.CardBuilder;
import java.io.File;
import java.io.IOException;
public class RecordActivity extends Activity {
private static final int CAMERA_VID_REQUEST = 1337;
static final int REQUEST_VIDEO_CAPTURE = 1;
public VideoView mVideoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_record);
takeVideo();
}
private void takeVideo(){
Intent startVideo = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (startVideo.resolveActivity(getPackageManager()) != null){
startActivityForResult(startVideo, REQUEST_VIDEO_CAPTURE);
}
//RecordActivity.this.startActivityForResult(startVideo, CAMERA_VID_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//System.out.println("Entered onActivityResult() method");
String a = getIntent().getStringExtra("record");
System.out.println(a);
if(requestCode == CAMERA_VID_REQUEST && resultCode == RESULT_OK) {
//System.out.println("Result Okay");
Uri videoUri = data.getData();
mVideoView.setVideoURI(videoUri);
String videoPath = data.getStringExtra(Intents.EXTRA_VIDEO_FILE_PATH);
processVideoWhenReady(videoPath);
}
super.onActivityResult(requestCode, resultCode, data);
}
protected void processVideoWhenReady(final String videoPath){
final File videoFile = new File(videoPath);
if (videoFile.exists()){
//Process Video
}
else {
final File parentDirectory = videoFile.getParentFile();
FileObserver observer = new FileObserver(parentDirectory.getPath(), FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
private boolean isFileWritten;
#Override
public void onEvent(int event, String path) {
if (!isFileWritten) {
//make sure file was created in directory expected
File affectedFile = new File(parentDirectory, path);
isFileWritten = affectedFile.equals(videoFile);
if (isFileWritten) {
stopWatching();
runOnUiThread(new Runnable() {
#Override
public void run() {
processVideoWhenReady(videoPath);
}
});
}
}
}
};
observer.startWatching();
}
}
}
I have three Activity objects.
I want to transfer picture from FirstActivity To SecondActivity by passing in AlarmREceiver
This is my code of FirstActivity
package com.testcamera.hassanechafai.testcamera;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class FirstActivity extends ActionBarActivity {
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
ImageView imgView;
private String imgPath;
Intent myIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
imgView = (ImageView) findViewById(R.id.ImageView);
Button butCamera = (Button) findViewById(R.id.Button1);
butCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
Button butGallery = (Button) findViewById(R.id.Button2);
butGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, ""),
PICK_IMAGE);
}
});
final EditText save = (EditText) findViewById(R.id.EditText1);
Button myBtn = (Button) findViewById(R.id.Save);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int time = Integer.parseInt(save.getText().toString());
if (time > 0) {
myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, time);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "Starting Activity in: " + time + " seconds", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgView.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgView.setImageBitmap(decodeFile(selectedImagePath));
Intent intent = new Intent(this, CallActivity.class);
intent.putExtra("BitmapImage", selectedImagePath);
} else {
super.onActivityResult(requestCode, resultCode,
data);
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
This code of AlarmReceiver
package com.testcamera.hassanechafai.testcamera;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm time reached", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClassName("com.testcamera.hassanechafai.testcamera", "com.testcamera.hassanechafai.testcamera.CallActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
This code of SecondAcitivy (I call it CallActivity)
package com.testcamera.hassanechafai.testcamera;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class CallActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
ImageView image = (ImageView)findViewById(R.id.ImageView);
}
I need to transfer photo from FirstActivity To SecondAcitivy by passing in AlarmActivity can someone help me ?
in your myBtn onClick you forgot to add myIntent.putExtra("theKeyUsed","yourConvertedStringUri");
then in your Receiver class you are missing that too.
IN your CallAcitvity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
String path = getIntent().getStringExtra("theKeyUsed"); // in your case "BitmapImage"
ImageView image = (ImageView)findViewById(R.id.ImageView);
// now set image using the path
}
In general pass your uri.toString() as a string extra with your intent to the preferred activity and retrieve..
feel free to delete the question if you find your solution
I am still having problems with my TextToSpeech android, I entered the button twice once for the implemented Speech like exlipse asked me too and one for the implemented OnClickListener, Even if I take out the bottom action for the button it doesn't want to play, Why? idk it just doesn't want to say what is in my EditText Field I have no clue why it doesn't want to and I have asked around many times but I haven't goten an answer that worked.
package com.write.it;
import java.util.HashMap;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Speech extends Activity implements OnInitListener, OnUtteranceCompletedListener, OnClickListener {
private EditText words = null;
private Button speakBtn = null;
private static final int REQ_TTS_STATUS_CHECK = 0;
private static final String TAG = "TTS Demo";
private TextToSpeech mTts;
private int uttCount = 0;
private HashMap<String, String> params = new HashMap<String, String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
words = (EditText)findViewById(R.id.wordsToSpeak);
speakBtn = (Button)findViewById(R.id.speak);
// Check to be sure that TTS exists and is okay to use
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, REQ_TTS_STATUS_CHECK);
}
public void doSpeak(View view) {
StringTokenizer st = new StringTokenizer(words.getText().toString(),",.");
while (st.hasMoreTokens()) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,
String.valueOf(uttCount++));
mTts.speak(st.nextToken(), TextToSpeech.QUEUE_ADD, params);
}
speakBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.speak:
doSpeak(v);
break;
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_TTS_STATUS_CHECK) {
switch (resultCode) {
case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS:
// TTS is up and running
mTts = new TextToSpeech(this, this);
Log.v(TAG, "Pico is installed okay");
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
// missing data, install it
Log.v(TAG, "Need language stuff: " + resultCode);
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL:
default:
Log.e(TAG, "Got a failure. TTS not available");
}
}
else {
// Got something else
}
}
public void onInit(int status) {
// Now that the TTS engine is ready, we enable the button
if( status == TextToSpeech.SUCCESS) {
mTts.setOnUtteranceCompletedListener(this);
speakBtn.setEnabled(true);
}
}
#Override
public void onPause()
{
super.onPause();
// if we're losing focus, stop talking
if( mTts != null)
mTts.stop();
}
#Override
public void onDestroy()
{
super.onDestroy();
mTts.shutdown();
}
public void onUtteranceCompleted(String uttId) {
Log.v(TAG, "Got completed message for uttId: " + uttId);
Integer.parseInt(uttId);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.speak:
doSpeak(v);
break;
}
}
}
Did you try speaking the text with just one method call? Like this
mTts.speak(aString, TextToSpeech.QUEUE_ADD, null);
It works fine for me. The initialization I use is the same as yours. The only remaining difference is this (which should not be necessary to get the TTS to work!):
this.speaker.setSpeechRate(0.9f);
this.speaker.setPitch(0.9f);
How can i open Android device contacts list at button click event.
Try this code..
yourButton.setOnClickListener(new YouButtonEvent());
class YouButtonEventimplements OnClickListener{
#Override
public void onClick(View v) {
Intent it= new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(it, PICK_CONTACT);
}
}
Declare Some variables. Create a method & handle the events.
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = "Contact List";
private static final int RESULT_OK = -1;
// a method to open your contact list
private void openContactList() {
Intent it = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(it, CONTACT_PICKER_RESULT);
}
// handle after selecting a contact from the list
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
// handle contact results
Log.w(DEBUG_TAG, "Warning: activity result is ok!");
break;
}
} else {
// gracefully handle failure
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
You can use this source code as a reference:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test1Activity extends Activity {
private static final int PICK_CONTACT_REQUEST = 1;
private static final int PICK_CONTACT = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button pickContact = (Button) findViewById(R.id.button1);
pickContact.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
startActivity(i);
}
});
}
}
if u want to pick contact from your device then use this code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContect();
dialog.dismiss();
}
and openContact() is:
private void openContect() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_CONTACT);
}
}
and in your onActivityResult() use this:
if (requestCode==REQUEST_SELECT_CONTACT && resultCode == RESULT_OK && null != data){
Uri contactUri = data.getData();
//do what you want...
}
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