Android Studio - Problem when playing audio

1

Good morning. I'm doing a simple test where I press a button and a sound plays. When emulating the application (or using it in the mobile) and clicking the button, the app is peta and closes. I think the problem is that it does not find the audio file, because I have another method in which I play a sound that I record and it does not give me any problem, since that audio is created by the app itself and I know where it is. The code is this:

Definition of the button in XML

public void soundTest (View view) {
        mediaPlayer = new MediaPlayer(); 
        mediaPlayer.create(this, R.raw.test);
        try {
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "Fallo en reproducción");
        }
    }

The function that the button calls

<Button
        android:id="@+id/sound"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Sound"
        android:onClick="soundTest"/>

I have created the folder "raw" and the file "test.mp3" is in it. Do not throw me any errors

    
asked by Gronin 04.10.2017 в 12:59
source

2 answers

1

In this case, you should not use prepare() and then start() or vice versa:

mediaPlayer.prepare();
 mediaPlayer.start();

You must use the listener OnPreparedListener() to determine when the MediaPlayer is ready to play and thus call the start() method to start playback:

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer arg0) {
        //Inicia reproducción.
        mediaPlayer.start();
    }
});

The complete code would be:

public void soundTest (View view) {
        mediaPlayer = new MediaPlayer(); 
        mediaPlayer.create(this, R.raw.test);
        try {
              mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
              @Override
              public void onPrepared(MediaPlayer arg0) {
                  //Inicia reproducción.
                  mediaPlayer.start();
              }
          });
        } catch (IOException e) {
            Log.e(LOG_TAG, "Fallo en reproducción");
        }
    }
    
answered by 04.10.2017 в 14:17
0

Do not instancies the MediaPlayer class, use this statement of a line that I'm going to put you.

I suppose you have a class variable declared in your variable zone such that:

MediaPlayer mediaPlayer;

Delete it and try this in your method, it should work:

public void soundTest (View view) {
      MediaPlayer  mediaPlayer = MediaPlayer.create(this, R.raw.test);
      try {
          mediaPlayer.prepare();
          mediaPlayer.start();
      } catch (IOException e) {
          Log.e(LOG_TAG, "Fallo en reproducción");
      }
 }
    
answered by 04.10.2017 в 14:01