So I put an audio file in my application and it's supposted play when I touch the button and stop when I touch it again.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button one = (Button) findViewById(R.id.buttonId);
final MediaPlayer mp = new MediaPlayer();
one.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
}
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("mosq.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.setLooping(true);
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
here is my code, this part:
if(mp.isPlaying())
{
mp.stop();
}
didn't work for some reason.
Make sure you put a return statement below mp.stop().
From what I can understand the sound does stop but then it starts again because the next part of the code still gets executed
As George D correctly pointed out, you start the media playing unconditionally, even if you just stopped it. You could use his solution or do something like:
if(mp.isPlaying())
{
mp.stop();
}
else {
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("mosq.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.setLooping(true);
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This has several other potential bugs in it:
* I'm not sure if this is what you intended but the player won't ever pause, just stop and restart from the beginning. If you try to resume or play again it'll completely reload the audio file every time. At a minimum this is a waste of resources, plus it's likely not the expected behavior from a UI perspective.
* You don't want to define the MediaPlayer object as a local variable within the OnCreate method. The only reason this works at all is you have a memory leak (you never unsubscribe your event handler for the click); if you didn't have the memory leak the object would become eligible for garbage collection as soon as you completed the onCreate method and, as far as the framework was concerned, it would no longer exist.
I keep getting null pointer exceptions for methods of MediaPlayer. I was finally able to get the play function to work by moving the code for play and initialize of play functions into a separate method and call that method from inside the onClick listener.
However am still getting null pointer exception for the apps pause function. I am using pause method of media player. How to the get pause to work? I think the problem is somewhere in the structure of my code and how it is organized.
I tried moving the initialization of the Media player to a different place in the code. and and nothing seems to work. Any ideas?
// onclick listener for the playing the selected song
playB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
playSong();
}
});
// onclick listener for pausing the song that is playing
pauseB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pauseSong();
}
});
// method to pause song
public void pauseSong(){
player.pause();
length = player.getCurrentPosition();
}
// method to play song and initialize the MediaPlayer class with one file
// from the drawable folder, need to initialize with something or it will be null
// for that i decided to use an mp3 in R.raw folder
public void playSong(){
// Play song
MediaPlayer player = MediaPlayer.create(this, R.raw.g2);
player.reset();
try {
player.setDataSource(selectedAudioPath);
player.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.seekTo(length);
player.start();
} // play method
You have to make a MediaPlayer player global variable. player is not visible for the pauseSong() method therefore you have nullPointerException. Create a MediaPlayer player in your main class and then in onPlaySong() initialize it only like this:
player = MediaPlayer.create(this, R.raw.g2);
I have been trying to develop an Andriod app of a simple sound board, which will play several long sounds, and only one at a time, not simultaneously. I can easily do a soundboard that uses repetitive code and many mediaplayers, but that will likely crash many devices due to allocating too many instances of MediaPlayer. I want to use a map so that I only use one mediaplayer, but after several hours, I’m still having compile problems. I could also use the App Inventor at MIT, but I don’t think I could upload that to market place without extensive key/signing hacks, so I don’t think that is a good option.
Does anyone know if there a working code example with just a couple of sounds that use just 1 mediaplayer included with the SDK, or available online? If I could start with just a basic working design, it would save me so much time.
My code looks like the below:
public class newBoard extends Activity {
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
*//below line causes an error due to use of "newboard"*
setContentView(R.layout.newboard);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
//just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.button01, R.id.button02, R.id.button03,
R.id.button04, R.id.button05, R.id.button06,
R.id.button07, R.id.button08, R.id.button09,
R.id.button10, R.id.button11, R.id.button12,
R.id.button13, R.id.button14, R.id.button15,
R.id.button16, R.id.button16, R.id.button17,
R.id.button18, R.id.button19, R.id.button20,
R.id.button21, R.id.button22, R.id.button23,
R.id.button24, R.id.button25 };
final int[] soundIds = { R.raw.sound01, R.raw.sound02, R.raw.sound03,
R.raw.sound04, R.raw.sound05, R.raw.sound06,
R.raw.sound07, R.raw.sound08, R.raw.sound09,
R.raw.sound10, R.raw.sound11, R.raw.sound12,
R.raw.sound13, R.raw.sound14, R.raw.sound15,
R.raw.sound16, R.raw.sound16, R.raw.sound17,
R.raw.sound18, R.raw.sound19, R.raw.sound20,
R.raw.sound21, R.raw.sound22, R.raw.sound23,
R.raw.sound24, R.raw.sound25 };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
//set the same listener for every button ID, no need
//to keep a reference to every button
for(int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button)findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
}
I have only one error:
newboard cannot be resolved, or is not a field Type: Java problem
A nice project download that could be used as a foundation would be optimal, if that exists!
Thanks in advance for any guidance!
Maytag87
The error means that it can't find your layout XML file.
Does the file /res/layout/newboard.xml exist in your Eclipse project? Perhaps the layout is called something else, like main.xml, in which case you should use R.layout.main in your Java code when you call setContentView().
in one activity I have 5 buttons. Each of these buttons make a different sound.
atm I'm doing on each buttonClicked method:
MediaPlayer mp = MediaPlayer.create(this, R.raw.click);
if(mp != null) mp.start();
MediaPlayer mp = MediaPlayer.create(this, R.raw.click2);
if(mp != null) mp.start();
etc..
is this the right way to do it, and I wonder since mp is local object, doesn't it die when the method dies, ergo no need to call mp.release() ?
note: my sounds are 0.5 sec or less and they seem to complete more often than not (haven't tested in many devices though). I'm targeting 2.1+
You need to declare your Mediaplayer reference globally need to assign mediaplayer object in the onCreate() then in button click call MediaPlayer.create(this/getApplicationContext(),R.Raw.yourfile); follow http://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram
mp.reset();
mp=MediaPlayer.create(getApplicationContext(),R.raw.hummingbird);
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
i have created an app with music buttons.the app is running with no problem in the emulator of eclipse but as i use my samsung galaxy s for emulator i have a force down error as i press any button..this is my logcat when i press a btn:
![alt text][1]
this is my code from 56-86 line
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
if(mp2.isPlaying()==true||mp3.isPlaying()==true||mp4.isPlaying()==true||mp5.isPlaying()==true||mp6.isPlaying()==true||mp7.isPlaying()==true||mp8.isPlaying()==true||mp9.isPlaying()==true||mp10.isPlaying()==true||mp11.isPlaying()==true||mp12.isPlaying()==true)
{mp2.stop();
mp3.stop();mp4.stop();mp5.stop();mp6.stop();mp7.stop();mp8.stop();mp9.stop();mp10.stop();mp11.stop();mp12.stop();
try {
mp2.prepare();
mp3.prepare();
mp4.prepare();
mp5.prepare();mp6.prepare();mp7.prepare();mp8.prepare();mp9.prepare();mp10.prepare();
mp11.prepare();mp12.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
Toast.makeText(a.this, "Eisai", Toast.LENGTH_SHORT).show();
}
else
mp.start();
Toast.makeText(a.this, "Eisai sto myalo", Toast.LENGTH_SHORT).show();
}
});
Is your "if" statement line 58? (Assuming you've noted the line range correctly, it should be.) Set a debug breakpoint on that line, and inspect all of your mp* variables. Most likely one of them is null. As a side note, for clearer code, you might want to try using an ArrayList<MediaPlayer> to store all those MediaPlayer objects.
EDIT: You can find the ArrayList documentation here.
Basically:
List<MediaPlayer> mediaPlayers = new ArrayList<MediaPlayer>();
//I have no idea how you're currently making the MediaPlayers,
//so modify accordingly.
mediaPlayers.add(MediaPlayer.create(Context, Uri));
Then, you can just use something like:
public void stopAllIfPlaying(ArrayList<MediaPlayer> mps) {
for (MediaPlayer mp : mps) {
if(mp.isPlaying()) mp.stop();
}
}
And instead of your if statement and stop statements, use something like this:
stopAllIfPlaying(mediaPlayers);
Then do something similar with your prepare statements.
Next time when you post a stacktrace, what happens BEFORE the NPE is a lot better than what happens after... But it's pretty obvious that Button button = (Button) findViewById(R.id.btn1) is returning null. Make sure your XML is correct and there's actually a button there.