I am writing a small practice app that plays a sound clip when a button is tapped. In my previous code, this amounts to just the creation of a MediaPlayer object and a call to mp.start() to start the audio.
This works, but now I would like that same button to play only when no sound is playing yet. If sound is playing, stop the audio. A play/stop button.
I tried to do this using the following code:
```
public class MainActivity extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goButtonClicked(View v) {
if(mp == null) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.wordt);
}
if(mp.isPlaying()) {
mp.stop();
mp.release();
}
else {
mp.start();
}
}
}
```
However now when I run the app, the app crashes when I tap the button. Where did I go wrong?
Just change your code like this,
public void goButtonClicked(View v) {
if(mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.wordt);
}
....
}
What happens here is, MediaPlayer mp = ... means you are creating a local variable inside if condition. But still your field variable is null. And when the app executes the second if condition, it throws a NullPointerException.
You didn't initialize your first mp object, so you see nullPointerException,
and you can delete second mp object
Related
buttonMusic = findViewById(R.id.buttonMus);
musicSound = MediaPlayer.create(this, R.raw.music);
buttonClick();
}
private Button buttonMusic;
private MediaPlayer musicSound;
public void buttonClick() {
buttonMusic.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay(musicSound);
}
}
);
}
public void soundPlay(MediaPlayer sound) {
if (sound.isPlaying()) {
sound.stop();
}else {
sound.start();
sound.setLooping(true);
} }
Hello.
The code launches the music, is able to stop it, but it wont play again after pressing the play button, after pausing the song that is.
you aren't pausing song, you are stop()ing it. use sound.pause() for pausing :)
after stop() MediaPlayer you have to prepare it again, use prepare() or prepareAsync(). MediaPlayer.create( makes that for you at the beginning, also if you would create MediaPlayer using its constructor you would also want to prepare()/preapreAsync() before calling start() in onClick
check out state diagram of MediaPlayer
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
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();
}
I made an android application where you can click buttons to play sounds. Every time, you click the button, a new MediaPlayer is getting created and the problem is, when you push a button during another sound is still playing, they are playing at the same time, but I want, that the previous sounds stops when you push a button. I already tried this code but my application crashes every time I press the button:
MediaPlayer mp;
Button button;
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()){
mp.stop();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
}});
Is there a way to solve my problem?
It might be crashing because 'mp' is not initialized. Try this:
#Override
public void onClick(View v) {
//if mp exists and is playing...
if(mp != null && mp.isPlaying()){
mp.stop();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
}});
EDIT You could also avoid checking for null by initializing 'mp' when you declare it on top.
For instance, instead of checking if mp != null. Change your declaration of 'mp' from:
MediaPlayer mp;
to
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
and your onclick method could look like:
public void onClick(View v) {
if(mp.isPlaying()) {
mp.stop();
}
//start mp from beginning
}
It seems like starting too many MediaPlayer isn't good, because when i click the sounds a couple times, the app crashes. I already changed mp.start to mp.reset and release.
Notes
You have to release the player before creating a new one
I would not bet on isPlaying() check to stop the player; since you don't need it release it!
Code
#Override
public void onClick(View v) {
if(mp != null) {
mp.release();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
mp.start();
}});
Im making an app, and i want it to make a sound when a activity is opened , the sound file is in R.raw.sound_file , if someone could do some example code to make my app play a sound that would be great.
doesn't the android.media.MediaPlayer class do this?
Reference: http://developer.android.com/reference/android/media/MediaPlayer.html
Example: http://developer.android.com/guide/topics/media/index.html
Step 2 of the example says:
MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.start();
In your case, I'd use the onStart() inside your Activity class:
public class MyActivity extends Activity {
...
protected void onStart() {
super.onStart();
MediaPlayer mp = MediaPlayer.create(this, R.raw.sound_file_1);
mp.start();
}
...
}
I have experience using the MediaPlayer object for an android app I created, and I discovered the following:
Wav files have problems in MediaPlayer if they have a bitrate of 32kbps, but wav files of higher bit rates seem to play ok, even if it is a large wav file it will play ok as long as it has the higher bitrate.
If at all possible, use mp3 files for your audio, I encountered no problems whatsoever with mp3 audio files using the MediaPlayer object, so that is the best way to go, using google there are lots of different kinds of mp3 sounds available free from rings and dings, to dog barks, and cat meows, or whatever kind of sound you are looking for.
Try with my code, It's works perfectly. Also you need to have the sound file .wav en res/raw
public class PianoActivity extends Activity {
private MediaPlayer mediaPlayer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_piano);
setupUI();
}
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
private void setupUI() {
findViewById(R.id.doo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
managerOfSound();
}
});
}
private void managerOfSound() {
mediaPlayer = MediaPlayer.create(this, R.raw.doo);
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
} else {
mediaPlayer.stop();
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
}
});
}
}
I had the same problem.
this worked for me by using the application context as follows:
public class MyActivity extends Activity {
...
protected void onStart() {
super.onStart();
Context appContext = getApplicationContext();
MediaPlayer mp = MediaPlayer.create(appContext , R.raw.sound_file_1);
mp.start();
}
...
}
Also, don't forget to call mp.release() once you're done
Another,preferred option is to use the SoundPool class