-1

I'm trying to play a music sound when my application starts. I used the code:

MediaPlayer mp = new MediaPlayer();
        MediaPlayer.create(this, R.raw.counting1to5song);
        mp.start();

and the song is in res/raw folder. But when I install the application in my phone and then open, the app crashes!!!

Anyone can give me any help to get this sound properly function?

Karga
  • 21
  • 7
  • 1
    can you post the logcat ? – Umair Mar 31 '15 at 10:27
  • what is the logcat? how can i get that? sory, i don't know. – Karga Mar 31 '15 at 10:35
  • Window -> Show View -> Other -> Android -> Logcat – Amsheer Mar 31 '15 at 10:38
  • Have you tried looking at this question? http://stackoverflow.com/questions/4861859/implement-sound-in-android-application – d_z90 Mar 31 '15 at 10:40
  • All ready tried to looking to that question. But the app crashes when it starts too. I find Logcat in Android Studio but nothing apears. – Karga Mar 31 '15 at 11:47
  • You're missing any kind of error handling. Don't take for granted that all API calls will succeed. For example, `MediaPlayer.create` will return `null` if it fails, and `MediaPlayer.start` will throw an exception if you call it when the media player is in the wrong state. – Michael Mar 31 '15 at 15:30
  • All ready solved, i was trying play a .wav sound but now i tried with MP3 and i was suceeded – Karga Apr 01 '15 at 11:26

2 Answers2

1

use this code an try it:

MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.sound1);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
  • The same problem. The app crashes when starts. But when i put that code in "new MediaPlayer();" is saying that the variable is redundant. – Karga Mar 31 '15 at 11:48
1
  1. Create a new folder called "raw" inside "debug" folder. To create it, right-click on "debug" folder > new > directory > and in name it "raw":

To add files just drag the .wav/.mp3 files to "raw" folder.

  1. Import media player:
import android.media.MediaPlayer;
  1. Declare MediaPlayer global variable(s):
public MediaPlayer mp1;
  1. Inside onCreate method, assign the corresponding sounds:
mp1 = MediaPlayer.create(MainActivity.this, raw.my_sound_name);
  1. Finally, you can use methods:
mp1.start() / mp1.stop() / mp1.pause()
Pingolin
  • 3,161
  • 6
  • 25
  • 40
yasser
  • 43
  • 1
  • 1
  • 7