Related
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 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();
}
});
I am getting problems in playing audio(mp3) files this music files are like click sounds its residing at the raw folder, the problem is if there are many clicks at random intervals it throws an exception of nullPointer. It occurs anywhere when the click is done and anytime, is it related to the memory issue or MediaPlayer related problem, pls any suggestion will be appreceated.
Its simple media player object that i m calling, but its a games so on touch it plays the files, so in game i have many things to drag so i want a click sound at that time, sometime it works fine but when exceeds certain limit it throws null pointer exceptions. this is the code:
MediaPlayer mp= MediaPlayer.create(context,R.raw.soun1);
mp.start();
thats it:
just try this ::
MediaPlayer mp = new MediaPlayer();
mp= MediaPlayer.create(this,R.raw.soun1);
mp.start();
permission in manifest file:::
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
To play media player...we need two classes..
let us suppose mainactivity.java is our first file..
here we define two buttons - start_button & stop_button
mButton_start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mIntent=new Intent(MainActivity.this,maservice.class);
startService(mIntent);
}
});
mButton_stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mIntent=new Intent(MainActivity.this,maservice.class);
stopService(mIntent);
}
});
maservice.java is our another java file. Here we define media player and also there should be 3 methods: onCreate(), onStart(), onDestroy().
Here is the code:
MediaPlayer mPlayer;
#Override
public void onCreate()
{
super.onCreate();
mPlayer=MediaPlayer.create(this, R.raw.kyun);
mPlayer.setLooping(true);
}
#Override
public void onStart(Intent miIntent, int startid)
{
super.onStart(miIntent, startid);
mPlayer.start();
}
#Override
public void onDestroy()
{
super.onDestroy();
mPlayer.stop();
}
We also have to define these java files in manifest file
mainactivity.java is defined under activity tag
but maservice.java is defined under service tag
I got my answer, its SoundPool, especially created when the concern of game like application where the sound files are used continuously, so here we should use SoundPool except of MediaPlayer.
The issue is with the MP3 encoding. I tried with the same code, few work and few don't. So please try with a different one if it shows up the same error next time.
I'm working on a project in which I have to load 6 different sounds in one activity and play all sound on button click.The sound file are not so big,but the problem is that maybe they will be more.So my question is which is the fastest way to load sound files in a single activity.For test purposes I used res/raw folder to store the sound files and tried with two different method to play the files,but the result did not satisfied me.Here is the two different types of code :
Method 1:
Button first = (Button) findViewById(R.id.one);
Button second = (Button) findViewById(R.id.two);
first.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(SoundFXActivity.this, R.raw.drumtwo);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
}
});
second.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(SoundFXActivity.this, R.raw.drumone);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
}
});
Method 2:
private SoundPool spool;
private int soundID,soundID2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
spool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundID = spool.load(this, R.raw.drumone, 1);
soundID2 = spool.load(this, R.raw.drumtwo, 1);
Button three = (Button) findViewById(R.id.three);
three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sound();
}
});
}
public void Sound(){
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
spool.play(soundID, volume, volume, 1, 0, 1f);
};
But the problem is that the both methods are slow..I need to find a way a faster way to play the sounds..but now there is like almost a second after I click the button to play the sound.
Can you give me some advice how to play the sounda faster.Should I load them into a cache when the application starts or save them in database or somewhere else (I don't think database is a good option as a matter of fact,but I want to hear some suggestions).Or maybe load them from assets folder,but I think it still going to be slow.
So any ideas or suggestions?
Thanks in advance!
You could create the media players in your onCreate and then the buttons will just make them play. That would be the easiest solution, I would say.
Alternatively, depending on how important it is to you and how much work you want to do, you could consider using JetPlayer:
here's android development page for media:
http://developer.android.com/guide/topics/media/index.html
The page on the JetPlayer class:
http://developer.android.com/reference/android/media/JetPlayer.html
and the page on creating the JET files:
http://developer.android.com/guide/topics/media/jet/jetcreator_manual.html
If you implemented this it would likely work best but would definitely be the most work.
JetPlayer basically lets you have one audio file (i think it's a MIDI file) with multiple tracks that you mute and unmute as you please. I have no personal experience with it and have just read the docs some, but it seems like it would be very useful for any situation with more than one sound.
Edit: Also, it's worth mentioning this mailing list and in case the link ever changes this google search in case anyone is interested in android audio topics.
If you want to have the less delay you must use OpenSL in c++, From jelly bean is the faster sound player
SoundPool is working fine, you can see an example with the Hexiano project. However, you must preload the sounds into SoundPool, because it takes a lot of time to decode the file and store them in-memory before being able to use them. But once the sounds are loaded, there's no noticeable delay between key press and sound output.
I'm trying to create a simple Sound-board Android app, using ListView items as buttons. (Btw, I'm a novice programmer)
The idea is that I press a button, and a specific sound file plays. If I press any button while a sound is playing, it should first stop that sound and then start to play the new one.
Currently the sounds play without stopping any currently playing sounds, so that if I spam the buttons I get multiple sounds playing at the same time (and if I press too many at once, the app force closes).
I have tried using a few variations of:
if (mp.isPlaying()) {
mp.stop();
}
But according to what I read on a few other sources, I am creating multiple instances of the MediaPlayer class, and even though they have the same name the stop() method tries to stop on the latest instance of mp (in some cases it isn't even created yet).
I'm guessing my general implementation of the MediaPlayer class is wrong, but it's the best I could figure out to do.
Anyways, here's the relevant block of code:
public class soundTest extends Activity {
private ListView lv1;
private String lv_arr[]={"test 1","test 2","test 3","test 4","test 5"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
lv1.setAdapter(new ArrayAdapter<String>(this,R.layout.list_item, lv_arr));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
if (lv1.getItemAtPosition(position)=="test 1") {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.sound1);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
if (lv1.getItemAtPosition(position)=="test 2") {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(),R.raw.sound2);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
//And the rest of the sounds 3,4,5.
}
});
}
}
Any help would be appreciated, thanks.
Edit (22nd March):
I've found the following piece of code that should work:
mp.setDataSource(context, Uri.parse("android.resource://" + Config.PACKAGE + "/" + resId));
But, I can't figure out how the "Config.PACKAGE" part works. I just get an error "PACKAGE cannot be resolved, or is not a field".
I tried replacing "PACKAGE" with the package name, same error. I also tried:
try {
mp.setDataSource(getApplicationContext(),Uri.parse("android.resource://com.mptest/" + R.raw.test2));
} catch (IOException e) {
e.printStackTrace();
}
But I can't work what exactly to put in place of "//com.mptest/".
The global variable MediaPlayer needs to be set private static. This has caught me several times.
Don't use a global. Use the singleton pattern. That is what it is for, so that you can have exactly one instance w/o using a global variable.
There are lots of good examples of Java code for this pattern, start with http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html and you can't go wrong.
Consider keeping your MediaPlayer as a global variable instead of having multiple instances of it.
You might find a good reference in the VideoView Source, since it handles one MediaPlayer object and you may change content during playback.