Timer with individual Sound in Foreground - android

Hello I would like to develop an app in Android that displays
a countdown and plays an individual sound when it expires. The
app has to be in the foreground the whole time.
Problems are still the sound and the app in the foreground.
Unfortunately I have no idea, as I have only recently started
developing with Android.
Thanks for the help!
I have used this template and integrated a method loadMusic, how can I now pause this instead of stop and play music individually?
private void loadMusic() {
if (timerStatus == TimerStatus.PAUSED)
new Runnable() {
#Override
public void run() {
playSound(R.raw.sound1);
}
public void playSound(int sound1) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), (R.raw.sound2));
mp.start();
}
}.run();
}
My Sound class:
package de.codeyourapp.countdowntimer;
import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
public class Sound extends AppCompatActivity {
ImageView imageButton1, imageButton2, imageButton3, imageButton4;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sound);
imageButton1 = findViewById(R.id.iv_bowl1);
imageButton2 = findViewById(R.id.iv_bowl2);
imageButton3 = findViewById(R.id.iv_bowl3);
imageButton4 = findViewById(R.id.iv_bowl5);
MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.sound1);
MediaPlayer mediaPlayer2 = MediaPlayer.create(this, R.raw.sound2);
MediaPlayer mediaPlayer3 = MediaPlayer.create(this, R.raw.sound3);
MediaPlayer mediaPlayer4 = MediaPlayer.create(this, R.raw.sound5);
imageButton1.setOnClickListener(v -> mediaPlayer1.start());
imageButton2.setOnClickListener(v -> mediaPlayer2.start());
imageButton3.setOnClickListener(v -> mediaPlayer3.start());
imageButton4.setOnClickListener(v -> mediaPlayer4.start());
}
}

You can use CountDownTimer of android. You can check this post for help.
Destroy the timer in onPause() to ensure that the timer doesn't work on background.
As to sound - you can add a sound file in your asset folder and take help from this thread to learn how to play the sound.

Related

How to make letter sound on cliсking by them? [duplicate]

How do I get a button to play a sound from raw when click? I just created a button with id button1, but whatever code I write, all is wrong.
import android.media.MediaPlayer;
public class BasicScreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
}
Button one = (Button)this.findViewById(R.id.button1);
MediaPlayer = mp;
mp = MediaPlayer.create(this, R.raw.soho);
zero.setOnCliclListener(new View.OnClickListener() )
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.basic_screen, menu);
return true;
}
}
This is the most important part in the code provided in the original post.
Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
To explain it step by step:
Button one = (Button) this.findViewById(R.id.button1);
First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById, passing the Id we assigned to it (in this example's case: R.id.button1), to get the button that we need. We cast it as a Button so that it is easy to assign it to the variable one that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
This is how to initialize a MediaPlayer. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create() method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho. We declare it as final. Jon Skeet provided a great explanation on why we do so here.
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//code
}
});
Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener of our button one. Inside is only one method, onClick() which contains what instructions the button should do on click.
public void onClick(View v) {
mp.start();
}
To play the sound, we call MediaPlayer's start() method. This method starts the playback of the sound.
There, you can now play a sound on button click in Android!
Bonus part:
As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release() method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener to our mp like so:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//code
}
});
Inside the onCompletion method, we release it like so:
public void onCompletion(MediaPlayer mp) {
mp.release();
}
There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment or Activity that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.
Original Post
First. You should put your statements inside a block, and in this case the onCreate method.
Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.
Third, put the logic to play the sound inside the onClick.
In summary:
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BasicScreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
}
}
Tested and working 100%
public class MainActivity extends ActionBarActivity {
Context context = this;
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mp = MediaPlayer.create(context, R.raw.sound);
final Button b = (Button) findViewById(R.id.Button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
}
}
This was all we had to do
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
}
The best way to do this is here i found after searching for one issue after other in the LogCat
MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
Not releasing the Media player gives you this error in LogCat:
Android: MediaPlayer finalized without being released
Not resetting the Media player gives you this error in LogCat:
Android: mediaplayer went away with unhandled events
So play safe and simple code to use media player.
To play more than one sounds in same Activity/Fragment simply change the resID while creating new Media player like
mp = MediaPlayer.create(context, R.raw.sound_two);
and play it !
Have fun!
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
Button one;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.soho);
one = (Button)this.findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.start();
}
});
}
}
The audio must be placed in the raw folder, if it doesn't exists,
create one.
The raw folder must be inside the res folder
The name mustn't have any - or special characters in it.
On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.
Example:
private Button myButton;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mp = MediaPlayer.create(this, R.raw.gunshot);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
}
}
there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.
Nice!
MediaActionSound
A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs
use like:
fun playBeepSound() {
val sound = MediaActionSound()
sound.play(MediaActionSound.START_VIDEO_RECORDING)
}
Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MediaPlayer mp1 = MediaPlayer.create(this, R.raw.b1);
mp1.start();
}
});
Try this i think it will work
public class MainActivity extends AppCompatActivity {
public void clickMe (View view) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
mp.start();
}
create a button with a method could be called when the button pressed (onCreate),
then create a variable for (MediaPlayer) class with the path of your file
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
finally run start method in that class
mp.start();
the file will run when the button pressed, hope this was helpful!
Instead of resetting it as proposed by DeathRs:
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
we can just reset the MediaPlayer to it's begin using:
if (mp.isPlaying()) {
mp.seekTo(0)
}
An edge case: Above every answer is almost correct but I was stuck in an edge case. If any user randomly clicks the button multiple times within a few seconds then after playing some sound it doesn't respond anymore.
Reason: Initialize Mediaplayer object is very expensive. It also deals with resources (audio file) so it takes some time for it. When users randomly initialize and calling a method of MediaPlayer's methods like start(), stop(), release(), etc can cause IllegalStateException which I faced.
Solution: Thanks caw for his suggestion in the comment about Android-Audio.
It has just a simple two java classes (MusicManager.java, SoundManager.java).
You can use MusicManager.java if you want to play one-off sound files -
MusicManager.getInstance().play(MyActivity.this, R.raw.my_sound);
You can use SoundManager.java if you want to play multiple sounds frequently and fast -
class MyActivity extends Activity {
private SoundManager mSoundManager;
#Override
protected void onResume() {
super.onResume();
int maxSimultaneousStreams = 3;
mSoundManager = new SoundManager(this, maxSimultaneousStreams);
mSoundManager.start();
mSoundManager.load(R.raw.my_sound_1);
mSoundManager.load(R.raw.my_sound_2);
mSoundManager.load(R.raw.my_sound_3);
}
private void playSomeSound() {
if (mSoundManager != null) {
mSoundManager.play(R.raw.my_sound_2);
}
}
#Override
protected void onPause() {
super.onPause();
if (mSoundManager != null) {
mSoundManager.cancel();
mSoundManager = null;
}
}
}
In Java:
private void playBeepSound(){
MediaActionSound sound = new MediaActionSound();
sound.play(MediaActionSound.START_VIDEO_RECORDING);
}
All these solutions "sound" nice and reasonable but there is one big downside. What happens if your customer downloads your application and repeatedly presses your button?
Your MediaPlayer will sometimes fail to play your sound if you click the button to many times.
I ran into this performance problem with the MediaPlayer class a few days ago.
Is the MediaPlayer class save to use? Not always. If you have short sounds it is better to use the SoundPool class.
A save and efficient solution is the SoundPool class which offers great features and increases the performance of you application.
SoundPool is not as easy to use as the MediaPlayer class but has some great benefits when it comes to performance and reliability.
Follow this link and learn how to use the SoundPool class in you application:
https://developer.android.com/reference/android/media/SoundPool
Youtube: Save Solution
check if mp != null then use the current function:
MediaPlayer mpClick;
private void onClickSound() {
if(mpClick == null){
mpClick = MediaPlayer.create(context,R.raw.tap);
}
if(mpClick.isPlaying())
{
}
else
{
mpClick.start();
}
}
usage:
Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
onClickSound();
}
});

how to play same music file over and over again in android

My Android app has a music file that I want it playing when the Main Activity is started and I want the music file to restart when it finishes. So, basically I want it to loop over and over until the user has moved to a different activity.
Below is the class that starts the music file, but when the music is over, it does not restart ...
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
public class MainMenu extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
MediaPlayer mPlayer = MediaPlayer.create(MainMenu.this, R.raw.mmt_menu);
mPlayer.start();
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(!manager.isMusicActive())
{
mPlayer.start();
}
}
}
What do I need to do so that when the music stops it restarts again?
Thanks very much!
Call the function:
MediaPlayer.setLooping(true|false)
on the mediaplayerObject after you called MediaPlayer.prepare()
Example:
Uri mediaUri = createUri(context, R.raw.media); // Audiofile in raw
folder Mediaplayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(context, mediaUri);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.prepare();
mPlayer.setLooping(true);
mPlayer.start();

Soundpool mediaplayer or other methods to play short sound file on Android

I need to create a very simple instrument app.Just 7 buttons and 7 notes , a simple piano.I downloaded 7 different short wav files.I need to play them by clicking on button. And when I release the button the sound should stop. I know that it should have been easy but the samples I tried didnt work. There are lots of soundpool and mediaplayer code examples but when I tried them they didnt work and I am not sure if this is because of the soundfiles I downloaded or something else. During my research I found this example
Playing short .wav files - Android
But it didnt help. I already downloaded notes from this website
https://www.freesound.org/people/pinkyfinger/sounds/68448/
and uploaded them to raw folder. How can I play them?
According to the links this is the updated code but it stops playing after about 20 clicks.
package com.example.playaudio;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private MediaPlayer mp;
private MediaPlayer mp2;
private MediaPlayer mp3;
private MediaPlayer mp4;
private MediaPlayer mp5;
private MediaPlayer mp6;
private MediaPlayer mp7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
Button button1=(Button)findViewById(R.id.button_1);
Button button2=(Button)findViewById(R.id.button_2);
Button button3=(Button)findViewById(R.id.button_3);
Button button4=(Button)findViewById(R.id.button_4);
Button button5=(Button)findViewById(R.id.button_5);
Button button6=(Button)findViewById(R.id.button_6);
Button button7=(Button)findViewById(R.id.button_7);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
button5.setOnClickListener(this);
button6.setOnClickListener(this);
button7.setOnClickListener(this);
}
public void onClick(View v) {
int resId;
int resId2;
int resId3;
int resId4;
int resId5;
int resId6;
int resId7;
switch (v.getId()) {
case R.id.button_1:
resId = R.raw.a;
mp = MediaPlayer.create(this, resId);
mp.start();
break;
case R.id.button_2:
resId2 = R.raw.b;
mp2 = MediaPlayer.create(this, resId2);
mp2.start();
break;
case R.id.button_3:
resId3 = R.raw.c;
mp3 = MediaPlayer.create(this, resId3);
mp3.start();
break;
case R.id.button_4:
resId4 = R.raw.d;
mp4 = MediaPlayer.create(this, resId4);
mp4.start();
break;
case R.id.button_5:
resId5 = R.raw.e;
mp5 = MediaPlayer.create(this, resId5);
mp5.start();
break;
case R.id.button_6:
resId6 = R.raw.f;
mp6 = MediaPlayer.create(this, resId6);
mp6.start();
break;
case R.id.button_7:
resId7 = R.raw.p;
mp7 = MediaPlayer.create(this, resId7);
mp7.start();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
For a button click use this tutorial Sound Buttons
Or this one Playing audio
They are both helpful and should be what your looking for.
Create and initialise all your media players beforehand (not on the OnClick).
In the OnClick just start playing. Something like
mpx= new MediaPlayer();
mpx.reset();
mpx.setVolume(m_volume, m_volume);
mpx.setDataSource(YourMediaSource);
mpx.prepare();
And in the OnClick()
mpx.start();
And yes you can play more than one button together. For that you already do what you need: use a separate player for every note. The tricky part is going to be handling lengths of your sounds... I am not sure but can try in the OnClck something like:
if (!mpx.isPlaying())
mpx.start();

Play sound on button click android

How do I get a button to play a sound from raw when click? I just created a button with id button1, but whatever code I write, all is wrong.
import android.media.MediaPlayer;
public class BasicScreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
}
Button one = (Button)this.findViewById(R.id.button1);
MediaPlayer = mp;
mp = MediaPlayer.create(this, R.raw.soho);
zero.setOnCliclListener(new View.OnClickListener() )
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.basic_screen, menu);
return true;
}
}
This is the most important part in the code provided in the original post.
Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
To explain it step by step:
Button one = (Button) this.findViewById(R.id.button1);
First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById, passing the Id we assigned to it (in this example's case: R.id.button1), to get the button that we need. We cast it as a Button so that it is easy to assign it to the variable one that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
This is how to initialize a MediaPlayer. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create() method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho. We declare it as final. Jon Skeet provided a great explanation on why we do so here.
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//code
}
});
Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener of our button one. Inside is only one method, onClick() which contains what instructions the button should do on click.
public void onClick(View v) {
mp.start();
}
To play the sound, we call MediaPlayer's start() method. This method starts the playback of the sound.
There, you can now play a sound on button click in Android!
Bonus part:
As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release() method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener to our mp like so:
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//code
}
});
Inside the onCompletion method, we release it like so:
public void onCompletion(MediaPlayer mp) {
mp.release();
}
There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment or Activity that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.
Original Post
First. You should put your statements inside a block, and in this case the onCreate method.
Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.
Third, put the logic to play the sound inside the onClick.
In summary:
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class BasicScreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
}
}
Tested and working 100%
public class MainActivity extends ActionBarActivity {
Context context = this;
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mp = MediaPlayer.create(context, R.raw.sound);
final Button b = (Button) findViewById(R.id.Button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
}
}
This was all we had to do
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
}
The best way to do this is here i found after searching for one issue after other in the LogCat
MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
Not releasing the Media player gives you this error in LogCat:
Android: MediaPlayer finalized without being released
Not resetting the Media player gives you this error in LogCat:
Android: mediaplayer went away with unhandled events
So play safe and simple code to use media player.
To play more than one sounds in same Activity/Fragment simply change the resID while creating new Media player like
mp = MediaPlayer.create(context, R.raw.sound_two);
and play it !
Have fun!
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
MediaPlayer mp;
Button one;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.soho);
one = (Button)this.findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.start();
}
});
}
}
The audio must be placed in the raw folder, if it doesn't exists,
create one.
The raw folder must be inside the res folder
The name mustn't have any - or special characters in it.
On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.
Example:
private Button myButton;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mp = MediaPlayer.create(this, R.raw.gunshot);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
}
}
there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.
Nice!
MediaActionSound
A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs
use like:
fun playBeepSound() {
val sound = MediaActionSound()
sound.play(MediaActionSound.START_VIDEO_RECORDING)
}
Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MediaPlayer mp1 = MediaPlayer.create(this, R.raw.b1);
mp1.start();
}
});
Try this i think it will work
public class MainActivity extends AppCompatActivity {
public void clickMe (View view) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
mp.start();
}
create a button with a method could be called when the button pressed (onCreate),
then create a variable for (MediaPlayer) class with the path of your file
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
finally run start method in that class
mp.start();
the file will run when the button pressed, hope this was helpful!
Instead of resetting it as proposed by DeathRs:
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
we can just reset the MediaPlayer to it's begin using:
if (mp.isPlaying()) {
mp.seekTo(0)
}
An edge case: Above every answer is almost correct but I was stuck in an edge case. If any user randomly clicks the button multiple times within a few seconds then after playing some sound it doesn't respond anymore.
Reason: Initialize Mediaplayer object is very expensive. It also deals with resources (audio file) so it takes some time for it. When users randomly initialize and calling a method of MediaPlayer's methods like start(), stop(), release(), etc can cause IllegalStateException which I faced.
Solution: Thanks caw for his suggestion in the comment about Android-Audio.
It has just a simple two java classes (MusicManager.java, SoundManager.java).
You can use MusicManager.java if you want to play one-off sound files -
MusicManager.getInstance().play(MyActivity.this, R.raw.my_sound);
You can use SoundManager.java if you want to play multiple sounds frequently and fast -
class MyActivity extends Activity {
private SoundManager mSoundManager;
#Override
protected void onResume() {
super.onResume();
int maxSimultaneousStreams = 3;
mSoundManager = new SoundManager(this, maxSimultaneousStreams);
mSoundManager.start();
mSoundManager.load(R.raw.my_sound_1);
mSoundManager.load(R.raw.my_sound_2);
mSoundManager.load(R.raw.my_sound_3);
}
private void playSomeSound() {
if (mSoundManager != null) {
mSoundManager.play(R.raw.my_sound_2);
}
}
#Override
protected void onPause() {
super.onPause();
if (mSoundManager != null) {
mSoundManager.cancel();
mSoundManager = null;
}
}
}
In Java:
private void playBeepSound(){
MediaActionSound sound = new MediaActionSound();
sound.play(MediaActionSound.START_VIDEO_RECORDING);
}
All these solutions "sound" nice and reasonable but there is one big downside. What happens if your customer downloads your application and repeatedly presses your button?
Your MediaPlayer will sometimes fail to play your sound if you click the button to many times.
I ran into this performance problem with the MediaPlayer class a few days ago.
Is the MediaPlayer class save to use? Not always. If you have short sounds it is better to use the SoundPool class.
A save and efficient solution is the SoundPool class which offers great features and increases the performance of you application.
SoundPool is not as easy to use as the MediaPlayer class but has some great benefits when it comes to performance and reliability.
Follow this link and learn how to use the SoundPool class in you application:
https://developer.android.com/reference/android/media/SoundPool
Youtube: Save Solution
check if mp != null then use the current function:
MediaPlayer mpClick;
private void onClickSound() {
if(mpClick == null){
mpClick = MediaPlayer.create(context,R.raw.tap);
}
if(mpClick.isPlaying())
{
}
else
{
mpClick.start();
}
}
usage:
Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
onClickSound();
}
});

Android Mediaplayer Play/Stop help needed

I am trying to create my first android application and what I'm trying to accomplish here is to play a sound and then stop it via the same button.
It kind of works as it plays the sound when I click it and stops when I click it again but will not play when I click it the third time to start the sound again.
I'm eventually going to have a few sounds in here and so would like to know if how my project is laid out correctly? Can I save some time anywhere? Have I got something the wrong way round?
package test.soundy.com;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class TestActivity extends Activity {
private MediaPlayer sound;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sound = MediaPlayer.create(Test.this, R.raw.sound1);
Button test = (Button)this.findViewById(R.id.button1);
test.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (sound.isPlaying()) {
sound.stop();
} else {
sound.start();
}
}
});
}
}
Any help would be much appreciated, thanks.
WHEN START/PAUSE:
if(sound.isPlaying()){
sound.pause();
}else{
sound.start();
}
WHEN START/STOP:
if(sound.isPlaying()) {
sound.stop();
} else {
sound.reset();
sound.setDataSource(yourURL); //or InputStream etc.
sound.prepare();
sound.start();
}
Also you can use sound.seekTo(time) to skip to a position.
Remember when you want to play a new sound(or restart) you should first reset, setDataSource, prepare and then start it.
EDIT: get the FileDescripter
AssetManager assetManager=Context.getAssets();
AssetFileDescriptor fileDescriptor = assetManager.openFd("a2.mp3");
mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor());
EDIT: I haven't found a way to turn raw file into filedescriptor so I use the static method of MediaPlayer
MediaPlayer mediaPlayer = MediaPlayer.create(Activity.this,R.raw.a1);
mediaPlayer.setOnCompletionListener(new musicCompletionListener());
mediaPlayer.start();
private class musicCompletionListener implements OnCompletionListener {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
}
alse release the mediaplayer when stop it.
Have you tried resetting the MP?
if (sound.isPlaying()) {
sound.stop();
} else {
sound.reset();
sound.prepare();
sound.start();
}
Edited...
The full state diagram is here: http://developer.android.com/reference/android/media/MediaPlayer.html

Categories

Resources