I'm looking to do a very simple piece of code that plays a sound effect. So far I have this code:
SoundManager snd;
int combo;
private void soundSetup() {
// Create an instance of the sound manger
snd = new SoundManager(getApplicationContext());
// Set volume rocker mode to media volume
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the samples from res/raw
combo = snd.load(R.raw.combo);
}
private void playSound() {
soundSetup();
snd.play(combo);
}
However, for some reason when I use the playSound() method, nothing happens. The audio file is in the correct location.
Is there a specific reason you are using SoundManager? I would use MediaPlayer instead, here is a link to the Android Docs
http://developer.android.com/reference/android/media/MediaPlayer.html
then it's as simple as
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.combo);
mp.start();
Make a directory called "raw/" under the "res/" directory. Drag wav or mp3 files into the raw/ directory. Play them from anywhere as above.
i have also attempted using the top answer, yet it resulted in NullPointerExceptions from the MediaPlayer when i tried playing a sound many times in a row, so I extended the code a bit.
FXPlayer is my global MediaPlayer.
public void playSound(int _id)
{
if(FXPlayer != null)
{
FXPlayer.stop();
FXPlayer.release();
}
FXPlayer = MediaPlayer.create(this, _id);
if(FXPlayer != null)
FXPlayer.start();
}
I am a novice developer trying to make an audio player on android.
On Youtube (https://www.youtube.com/watch?v=hNbXrlrWzGY&list=PL9vy4y29rrd4x5pAbowit8gpjsXAai0yF&index=8),
I did the same way I implemented it at 18:19, but it was played in Youtube video, but I didn't.
I also tried applying the content here Media Player called in state 0, error (-38,0),
but the music still doesn't play.
Here is my code.
musicPlayer = new MediaPlayer();
MediaController controller = new MediaController(this);
try {
musicPlayer.setDataSource(song.getPath());
musicPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
String duration = millisecondsToString(musicPlayer.getDuration());`
What's the difference between that YouTube and the way I did it?
Thank you.
++I invoke start() in onClick()
public void onClick(View v) {
switch(v.getId()) {
case R.id.playbtn :
if(musicPlayer.isPlaying()) {
musicPlayer.pause();
playbtn.setBackgroundResource(R.drawable.resume);
} else {
musicPlayer.start();
playbtn.setBackgroundResource(R.drawable.play);
}
break;
Firstly sorry for my English.
Are you have invoked the method: player.start() ? .
If not,You need invoked it when player prepare successed.
It may be have a listener for when prepare Ready callback.
Invoke the player.start() when received the event.
Or invoke the player.autoStart() like it.
The method name maybe not to exit but maybe similar
I am new to game development, and i'm struggling a bit with combining the google play service realtime multiplayer functionality in my LibGDX game. I do not find a lot of tutorials regarding this online.
I have downloaded the BaseGameUtils library, and everything is connected (my signIn method works), and i'm using interfaces to combine the android package with my core package.
In my AndroidLauncher, i have this code:
#Override
public void startQuickGame() {
final int MIN_OPPONENTS = 1, MAX_OPPONENTS = 1;
Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(MIN_OPPONENTS, MAX_OPPONENTS, 0);
RoomConfig.Builder rtmConfigBuilder = RoomConfig.builder((RoomUpdateListener) this);
rtmConfigBuilder.setMessageReceivedListener((RealTimeMessageReceivedListener) this);
rtmConfigBuilder.setRoomStatusUpdateListener((RoomStatusUpdateListener) this);
rtmConfigBuilder.setAutoMatchCriteria(autoMatchCriteria);
//prevent screen from sleeping
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Games.RealTimeMultiplayer.create(gameHelper.getApiClient(), rtmConfigBuilder.build());
}
I try to use the code in my Menu class:
#Override
protected void handleInput() {
if (Gdx.input.justTouched() && isOnBtn()) {
try {
crush.playServices.startQuickGame();
} catch (Exception e) {
e.printStackTrace();
}
gsm.set(new OnlineMultiplayerState(gsm));
dispose();
I'm not sure about how i should actually start the game?
At this point, everything just go black.
I would also like to use the code for methods like
handleSelectPlayersResult(int response, Intent data)
The problem is that when i try to define this method in my interface, it wont work because Intent only work in the Android package (not in core where my interface is).
Do you have an suggestion to how i can solve this?
Thank You!
i have read many threads on this topic and tried to use them in my code but i am still not able to solve it.
What i am trying to do:
Like facebook or any other app which downloads feed from server which includes image, I am also doing same and trying to display feeds and images on the image view.
What is happening:
I am able to download the feeds (in JSON) which includes URL of images and i am able to show them on ImageView.
In Emulator my MAX heap size is 64MB. I am consuming around 30MB in first 10 feeds( not sure why but this is what i get from Memory tab in Android monitor of Android Studio and Even in Android Device monitor).
I have a refresh button in my app which reloads the same feeds after removing all feeds which were earlier populated. I expected that i will be consuming the same memory or some what more. But contrary to that my memory usage got increased upto 42MB. Hence after tapping on refresh for 3 to 4 times, it is causing OutOFMemory Execption. Even if i load next 10 feed or 50 feeds at a time i am getting OutOfMemory Exception.
I know that facebook instagram and many more such apps does the same thing but not sure how they implemented the code to cover this situation.
Below is my code for populating feed
private void loadFeed(List<Feed> feedList)
{
Log.v(Constant.TAG,"Loading Feed in social feed page");
for(final Feed feed:feedList) {
LinearLayout feedBox = new LinearLayout(this);
feedBox.setOrientation(LinearLayout.VERTICAL);
FrameLayout profileDetailContainer= new FrameLayout(this);
LinearLayout profileDetailContainerParent=new LinearLayout(this);
LinearLayout profileDetailContainerChild=new LinearLayout(this);
profileDetailContainerChild.setOrientation(LinearLayout.VERTICAL);
ImageView imgProfile= new ImageView(this);
TextView txtDate= new TextView(this);
TextView txtName= new TextView(this);
ImageView imgProduct= new ImageView(this);
txtName.setText(feed.getUserFullName());
TextView txtDesciption= new TextView(this);
txtName.setTypeface(null, Typeface.BOLD);
if(feed.getDescription().length()>Constant.NUMBER_OF_DESCRIPTION_CHAR_SHOW_ON_RESULT)
{
txtDesciption.setText(feed.getDescription().substring(0,Constant.NUMBER_OF_DESCRIPTION_CHAR_SHOW_ON_RESULT)+"...");
}
else
txtDesciption.setText(feed.getDescription());
if(!IOUtil.fileExists(this,feed.getProductImageName())) {
WebRequest request = new WebRequest();
request.setUrl(Constant.ROOT_APPLICATION_URL_WITH_SEPARATOR + feed.getImgPath());
request.setParam(feed.getId() + "");
new ImageDownloadTask(this, true, feed.getProductImageName(), this).execute(request);
Log.v(Constant.TAG,"URL:"+Constant.ROOT_APPLICATION_URL_WITH_SEPARATOR+feed.getImgPath());
Picasso.with(getApplicationContext()).load(R.drawable.logo).into(imgProduct);
feedBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ScreenUtility.alertException(v.getContext(),"Please wait untill product image loads");
}
});
PixyfiSession.save(feed.getId() + "", imgProduct);
PixyfiSession.save(feed.getId() + "_feed", feed);
}
else
{
ImageUtil.recycleIfPossible(imgProduct);
try {
imgProduct.setImageBitmap(ImageUtil.getLocalImage(feed.getProductImageName(),this));
FeedboxOnClickListener feedboxOnClickListener = new FeedboxOnClickListener(feed);
feedBox.setOnClickListener(feedboxOnClickListener);
} catch (FileNotFoundException e) {
Log.v(Constant.TAG,e.getMessage(),e);
}
}
if(FacebookUtil.localProfilePicExists(feed.getUserName(),this))
{
Bitmap profileImage= FacebookUtil.getLocalProfilePicture(feed.getUserName(),this);
imgProfile.setImageBitmap(profileImage);
}
else {
FacebookUtil.loadProfilePicture(feed.getUserName(),this,this);
PixyfiSession.save(feed.getUserName(),imgProfile);
imgProfile.setImageResource(R.drawable.profile);
}
try {
if(feed.getDate()==null) {
txtDate.setText(new SimpleDateFormat("dd MMM yyyy").format(new SimpleDateFormat("yyyy-MM-dd").parse(feed.getFeedDate())));
}
else {
txtDate.setText(new SimpleDateFormat("dd MMM yyyy").format(feed.getDate()));
}
} catch (ParseException e) {
Log.e(Constant.TAG,e.getMessage(),e);
}
LinearLayout.LayoutParams layoutParam= new LinearLayout.LayoutParams(140,140);
layoutParam.setMargins(5,5,0,0);
imgProfile.setLayoutParams(layoutParam);
layoutParam= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,Gravity.TOP|Gravity.LEFT);
layoutParam.setMargins(20,5,0,0);
txtName.setLayoutParams(layoutParam);
layoutParam= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,Gravity.LEFT);
layoutParam.setMargins(20,5,0,0);
txtDate.setLayoutParams(layoutParam);
profileDetailContainerParent.addView(imgProfile);
profileDetailContainerChild.addView(txtName);
profileDetailContainerChild.addView(txtDate);
profileDetailContainerParent.addView(profileDetailContainerChild);
feedBox.addView(profileDetailContainerParent);
LinearLayout.LayoutParams feedLayoutParam=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT,Gravity.CENTER_VERTICAL);
feedLayoutParam.setMargins(5,5,5,5);
imgProduct.setLayoutParams(feedLayoutParam);
txtDesciption.setLayoutParams(feedLayoutParam);
feedBox.addView(txtDesciption);
feedBox.addView(imgProduct);
feedLayoutParam=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT,Gravity.CENTER_VERTICAL);
feedLayoutParam.setMargins(0,5,0,5);
feedBox.setLayoutParams(feedLayoutParam);
feedBox.setBackgroundColor(Color.parseColor("#cccccc"));
PixyfiSession.save(feed.getId()+"_feedbox",feedBox);
imgProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PixyfiSession.save(Constant.SELECTED_USER_ID,feed.getUserName());
ScreenUtility.loadScreen(v.getContext(),UsersProfile.class,false);
}
});
this.feedContainer.addView(feedBox);
}
if(feedList.size()==Constant.FEED_SIZE_IN_ONE_REQUEST)
{
Button moreFeed= new Button(this);
moreFeed.setText("Load MOre Feed");
moreFeed.setOnClickListener(new MoreFeedButtonListener(this));
this.feedContainer.addView(moreFeed);
}
this.progressBar.setVisibility(View.INVISIBLE);
}
For reloading/refreshing the feed
this.currentPage=1;
this.recycleImages();
this.feedContainer.removeAllViews();
PixyfiSession.save(Constant.CURRENT_FEED_PAGE,this.currentPage);
this.progressBar.setVisibility(View.VISIBLE);
loadFeed();
recycleImages Method:
private void recycleImages()
{
for(int i=0;i<this.feedContainer.getChildCount();i++)
{
if(this.feedContainer.getChildAt(i) instanceof ImageView)
{
ImageView view=(ImageView)this.feedContainer.getChildAt(i);
ImageUtil.recycleIfPossible(view);
}
}
}
If you need further details on the code then please let me know.
Also is it possible to see memory usage of other apps like facebook in android device monitor?
UPDATE
ImageUtil.getLocalImage Method
public static Bitmap getLocalImage(String imageName, Context context) throws FileNotFoundException
{
Bitmap bitmap=null;
InputStream is=null;
if(IOUtil.fileExists(context,imageName)) {
is = context.openFileInput(imageName);
bitmap= BitmapFactory.decodeStream(is);
}
else {
throw new FileNotFoundException("Image file doesn't exists");
}
return bitmap;
}
I am adding the answer :
Instead of managing the view components yourself you should always prefer listview or better recycler view.
Because it help you avoid view leaks and provide better reuse of views that you already created.
i had same problem add this line to your manifest in application tag:
<application
android:largeHeap="true"
.
.
.
As Saber Safavi told do that first and then add
defaultConfig {
....
multiDexEnabled true
....
}
in your
app/build.gradle
file..
Look like you have problem with loading images. Please check your ImageUtils.getLocalImages, did you decode and load a scaled version of images into memory, or did you load original images into memory?
Follow this document from Android developer , i think it's the best tutorial for loading images efficiently in Android.
Image handling in Android is very very tricky. Better use a library which has been built to take care of the situation and complexities involved.
I prefer
UniversalImageLoader or Piccaso!
It is because you are keeping too many bitmap images in Run-time memory, try not to create too many images and try nullifying them.
Mobile devices typically have constrained system resources. Android devices can have as little as 16MB of memory available to a single application. Virtual Machine Compatibility gives the required minimum application memory for various screen sizes and densities. Applications should be optimized to perform under this minimum memory limit. However, keep in mind many devices are configured with higher limits.
I will not recommend you for the heapSize flag in android manifest. I hope you are not developing games :), Rather go for retrofit or any other image processing library if you want. I would suggest you to look at BitmapFun sample provided by Google. It is available on developer portal.
http://developer.android.com/training/displaying-bitmaps/index.html
Cheers!!
I am developing an Android App which requires speech to text conversion. Currently I have used Google voice search for this purpose but using google requires internet connection and moreover it gives highly inaccurate results for eg. when I say '1' it prints "when"..
Therefore, I want to define my own grammar such that when I give a voice command it searches the grammar defined by me to find the best possible match instead of searching the internet. Using grammar for speech recognition can be done easily for windows 8 phone but I want to know how I can make this work for Android phones.
Kindly take a look at below codes!..
**Using Intent:::**
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
Without Using Intent::
Step 1: Implement RecognitionListener in your class.
Step 2. Add the Below codes:
private SpeechRecognizer speech = null;
private Intent speechIntent=null;
/**
* Speech Result is used to Store the Voice Commands
*/
private ArrayList<String> speechResult;
inside onCreate() --- >
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
Trigger this after your button Click:
if (SpeechRecognizer.isRecognitionAvailable(this)) {
if(speechIntent==null ){
speechIntent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
speechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
speechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,12);
speech.startListening(speechIntent);
}else{
if(speech!=null){
speech.startListening(speechIntent);
}
}
}
Replace the onResults link this:
public void onResults(Bundle results) {
speechResult = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(speechResult!=null){
if(speechResult.size()>0 ){
String command=speechResult.get(0).toString();
}
}
}