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
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 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
i have coded for media player and it is playing song .In the front end only image button is used and hardcoded as play button
when i click again it has to change image to pause state but the button which i have used is playing the song two times simultaneously whenever i click on it which is wrong
but i need the song to be paused so whereever i used
mp.start();
function which will be start to play the music from the url i added the code as
if(!mp.isPlaying()){
mp.start();
buttonPlayPause.setBackgroundResource(R.drawable.pause);
}else {
mp.pause();
buttonPlayPause.setBackgroundResource(R.drawable.play);}
but when i click the play button it starts playing and again if i click the button again it starts playing two times simultaneously
please help me how should i start and pause the mp3 file which i have displayed it in url it is not going to else block itself should i use different function
the full code of the project is
public class MainActivity5 extends Activity implements OnClickListener,
OnPreparedListener, OnErrorListener, OnCompletionListener {
MediaPlayer mp;
ProgressDialog pd;
Button bt;
ImageButton iv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main5);
iv = (ImageButton)findViewById(R.id.play);
iv.setOnClickListener(this);}
#Override
public void onPrepared(MediaPlayer mp)
{
Log.i("StreamAudioDemo", "prepare finished");
//pd.setMessage("Playing.....");
//mp.start();
/*if(mp.isPlaying()== true)
{
mp.start();
iv.setImageResource(R.drawable.pause);
}
else
{
mp.pause();
mp.release();
iv.setImageResource(R.drawable.play);
}*/
}
#Override
public void onClick(View v) {
try
{
pd = new ProgressDialog(this);
pd.setMessage("Buffering.....");
//pd.show();
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setDataSource("http://192.168.1.138/Android/music/vande.mp3");
mp.prepareAsync();
mp.setOnCompletionListener(this);
}
catch(Exception e)
{
Log.e("StreamAudioDemo", e.getMessage());
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
pd.dismiss();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
pd.dismiss();
Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
}}
thanks for your help in advance
i have commented some code above i have to re correct it
you can have a try at your onclickListener,when this player is playing,if you want to pause it ,you should to call MediaPlayer.pause() ,if you want to release it data,you can call MediaPlayer.release(),then ,you can play next music.
use this
public void onPrepared(MediaPlayer mp)
{
Log.i("StreamAudioDemo", "prepare finished");
//pd.setMessage("Playing.....");
// mp.start(); - this should be removed
if(mp.isPlaying()== true)
{
mp.pause();
iv.setImageResource(R.drawable.pause);
}
else
{
mp.start();
mp.release();
iv.setImageResource(R.drawable.play);
}
}