multiple mediaplayer sound crash android - java

I have multiple sounds i would like loaded
final MediaPlayer mp = MediaPlayer.create(this, R.raw.testsnd);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.testsnd2);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.testsnd3);
ect.
I have sound starts within clicklisteners
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}};
It has to be final as mp.start(); won't be seen within listeners
Is there a way to switch between the different sounds as mediaplayer will crash the app
if I use this more than once
Can set tag/ get tag be used if possible to make the switch?
Please help!

The MediaPlayer has a state machine that I believe you are ignoring. The static create methods are a shortcut for one-time deals. If you want the MediaPlayer to be used more than once, do something like this:
final MediaPlayer mp1 = new MediaPlayer();
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick() {
try {
mp1.reset();
mp1.setDataSource(YourClass.this,
Uri.parse("android.resource://com.your.package/" + R.raw.testsnd);
mp1.prepare();
mp1.start();
}
catch (Exception ex) {
// handle error
}
}
}
It should be trivial to replace your package and class names, and also to extrapolate the idea for multiple MediaPlayers. Chances are you only need one at any given time unless the sounds can be played at the same time. Also, don't forget to call release() when you are done.
If the sounds are brief, you may want to look into using SoundPool also.

I can`t understand why you do things like that, can you post more of your code? But if you need to play three sounds from your MediaPlayer instance you can try this:
private final MediaPlayer mpSound1;
private final MediaPlayer mpSound2;
private final MediaPlayer mpSound3;
private void playSound1(){
try{
if(mpSound1==null)
mpSound1 = MediaPlayer.create(this, R.raw.testsnd);
mpSound1.start();
}catch(Exception ex){
mpSound1 = null;
}
}
private void playSound2(){
try{
if(mpSound2==null)
mpSound2 = MediaPlayer.create(this, R.raw.testsnd2);
mpSound2.start();
}catch(Exception ex){
mpSound2 = null;
}
}
private void playSound3(){
try{
if(mpSound3==null)
mpSound3 = MediaPlayer.create(this, R.raw.testsnd3);
mpSound3.start();
}catch(Exception ex){
mpSound3 = null;
}
}

Related

Android - how to get resource by button tag?

I have 8 buttons in my Activity and 8 small audios in the res/raw directory. When one button is clicked, the app plays the audio associated with that particular button. I named each audio the same / similar to the associated button's tag. I want to have only one method in my activity that solves all cases.
This is what I have so far :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void playPhrase(View view){
if(view.getTag().toString().equals("doYouSpeak")){
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.doyouspeakenglish);
mediaPlayer.start();
}
else if(view.getTag().toString().equals("goodEvening")){
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.goodevening);
mediaPlayer.start();
}
// the other 6 cases
}
}
Is there a way to access the audios using the associated button tag (or id or anyhow) without the whole if/else statements ? Something like :
public void playPhrase(View view){
String tag = view.getTag().toString();
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.tag);
mediaPlayer.start();
}
You can use getIdentifier() method to get the id by String name.
String tag = view.getTag().toString();
Int id = getResources().getIdentifier(tag, "raw", getPackageName());
MediaPlayer mediaPlayer = MediaPlayer.create(this, id);
mediaPlayer.start();

Adding a sound to the onClick method

I would like to add a sound whenever the user clicks the apps button, any idea how can I do that?
I have tried to create a "raw" directory on the res/ file with different names, like for example "test.mp3", which did not work...
Playing sound is not difficult.
And as long as these are short sounds during app foreground operations it fine.
You need to use the MediaPlayer.
First, prepare it.
private MediaPlayer mMediaPlayer = null;
private MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
};
Now on click:
public void onItemClick(.........) {
releaseMediaPlayer();
mMediaPlayer = MediaPlayer.create(getActivity(),getSoundFileResID());
mMediaPlayer.setOnCompletionListener(mOnCompletionListener);
mMediaPlayer.start();
}
You need to implement the getSoundFileResID().
For more info read the MediaPlayer OverView

Play and pause Mediaplayer with variable

I'm trying to build an Android App where the user can play audiofiles labeled with an id from a database.
//get id from database and turn it into a string, add letter a, because its a res file
stringId = "a" + String.valueOf(standard.getId());
//find playbutton
final FloatingActionButton play = (FloatingActionButton) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//to be able to feed mediaplayer a variable I put it in another function called playAudio
playAudio(stringId, true); }
});
final FloatingActionButton pause = (FloatingActionButton) findViewById(R.id.pause);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playAudio(stringId, false); }
});
The playAudio looks like this:
private void playAudio(String nameOfFile, Boolean booleanPlay){
MediaPlayer mediaPlayer = MediaPlayer.create(this, getResources().getIdentifier(nameOfFile, "raw", getPackageName()));
if (booleanPlay = true){
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
if (booleanPlay = false){
mediaPlayer.pause();
}
}
When I run my code every time I press play it creates a new mediaplayer which starts playing at the same time as the other mediaplayer, the pause button doesn't work for the same reason. I can't figure out how to make it work.
Do not create a new MediaPlayer instance each time you play a new file. Create an instance at the beginning and reuse it:
private static MediaPlayer mediaPlayer = new MediaPlayer ();
When changing the file to play, try this piece of code:
AssetFileDescriptor afd = getApplicationContext ().getResources ().openRawResourceFd (R.raw.sound);
if (afd != null)
{
mediaPlayer.reset()
mediaPlayer.setDataSource(afd.getFileDescriptor (), afd.getStartOffset (), afd.getLength ());
mediaPlayer.setLooping (true);
mediaPlayer.prepare ();
mediaPlayer.start ();
}
Replace R.raw.sound with the filename of the sound to play (this would be in the res/raw folder) or use a different way to reference the file as needed.
That works for me -- tested on Android 8.1 (targeted). Hope this helps.
EDITED TO ADD: I just noticed you have wrong operators in the if(booleanPlay = false) and if (booleanPlay = true) statements. They should be == (comparison, instead of assignment).
And one last thing: When exiting, you should call mediaPlayer.release() to free up the resources, but you probably knew that. Glad I could help.

Playing a sound on android

I have come across another error along my first app journey :) I want to play a sound when the app loads. Which is a .wav file. It lasts 2 seconds long yet it does not play when I run the app on my old Samsung S4. There is no errors within the IDE or anything I can see, I have checked if 'mp' has a value and it does. Looking around on posts most people have the problem that 'mp' is = null. Whereas mine has a value just no sound comes out of the phone... Again, any help is appreciated!
public class OpeningScreen extends Activity {
#Override
// create the screen state
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// connect the xml layout file
setContentView(R.layout.activity_opening_screen);
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
mp.start();
// create the on touch listener
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.opening_layout);
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// change the screen to a new state
Intent intent = new Intent(OpeningScreen.this, GameScreen.class);
// start the new activity
startActivity(intent);
// stop welcome sound (if still playing)
mp.stop();
return true;
}
});
}
}
public static MediaPlayer create(Context context, int resid) is a static method to create a MediaPlayer for a given resource id.
It means that by calling create you are creating a new instance of media player with no reference usage.
Try to change
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
to
final MediaPlayer mp = MediaPlayer.create(this, R.raw. welcome_message);
And the player should work.
It's better to register for OnPreapredListener via MediaPlayer.setOnPreaparedListener and after preparation you start your media playback.
http://developer.android.com/guide/topics/media/mediaplayer.html
Why do you use final?
You can play a mp3 with
MediaPlayer mp = MediaPlayer.create(OpeningScreen.this, R.raw.welcome_message);
mp.start();
Also stopping mediaplayer is better if you stop in onDestroy.
public void onDestroy() {
mp.stop();
super.onDestroy();
}

Android: if statement not working with .isPlaying()

I created an onClick methord PlaySound in which an if statement checks weather the sound is playing or not , if it is playing it stops it or else it starts it.The problem i face is that the if statement is always false and never true.
CODE
public void PlaySound(View view) {
final MediaPlayer clickSound = MediaPlayer.create(this, R.raw.abcd);
if(clickSound.isPlaying()) {
clickSound.stop();
}
else{
clickSound.setLooping(true);
clickSound.start();
}
}
Remove
final MediaPlayer clickSound = MediaPlayer.create(this, R.raw.abcd);
from play method and create it outside of the method.
Edit for your convenince follow the steps:
You can take a global variable of MediaPlayer
public MediaPlayer clickSound ;
and then create in onCreate method:
clickSound = MediaPlayer.create(this, R.raw.abcd);
and thus your play method will be:
public void PlaySound(View view) {
if(clickSound.isPlaying()) {
clickSound.stop();
}
else{
clickSound.setLooping(true);
clickSound.start();
}
}

Categories

Resources