I wrote my own MediaPlayer class to play files at a specific path and to play files from the assets folder. Here is the class:
public class CMediaPlayer extends MediaPlayer{
public void play(String audioPath){
this.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
File f = new File(audioPath);
if(f.exists()){
try{
FileInputStream fis = new FileInputStream(f);
FileDescriptor fileD = fis.getFD();
this.setDataSource(fileD);
this.prepare();
}catch(IOException e){
}
this.start();
}
}
public void play(AssetFileDescriptor descriptor){
this.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
try {
this.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
this.prepare();
}catch (IOException e){
}
this.start();
}
}
I want to play several sounds with that class from an activity. Here is my code:
public class playGame extends Activity {
//a lot of variables
CMediaPlayer mediaPlayer; //declare my mediaplayer
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
//release??????
Intent myIntent = new Intent(getBaseContext(), startView.class);
startActivity(myIntent);
}
return super.onKeyDown(keyCode, event);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_question2);
mediaPlayer = new CMediaPlayer(); //define my mediaplayer
//stuff
}
//more variables
public void playQuestion(File question){
//stuff
TextView myTextView = (TextView) findViewById(R.id.textViewQuestion);
//stuff
myTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.play(pathSoundQuestion); //play sound when clicked
}
});
//stuff
myImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.play(pathSoundQuestion); //play sound when clicked
}
});
//stuff
mediaPlayer.play(pathSoundQuestion); //plays sound immediatly, first played sound (works fine)
//button1
Button myButton = (Button) findViewById(R.id.button1);
//stuff
myButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if(lastClickedButton == v){
//stuff
return;
}
//stuff
mediaPlayer.play(pathAudio1); //play sound when clicked (error)
}
});
//button2
myButton = (Button) findViewById(R.id.button2);
//stuff
myButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if(lastClickedButton == v){
//stuff
return;
}
//stuff
mediaPlayer.play(pathAudio2); //play sound, same problem
}
});
//goes on like this some more times...
}
public void logIn(View v, String right){
//stuff
if(right.equals("true")){
//stuff
try {
AssetFileDescriptor descriptor = getAssets().openFd("Right");
mediaPlayer.play(descriptor); //play sound from assets
Intent myIntent = new Intent(getApplication(), playGame.class);
startActivity(myIntent);
}catch (IOException e){
}
}else{
//stuff
try {
AssetFileDescriptor descriptor = getAssets().openFd("Wrong");
mediaPlayer.play(descriptor); //play sound from assets
Intent myIntent = new Intent(getApplication(), playGame.class);
startActivity(myIntent);
}catch (IOException e){
}
}
}
}
The app plays the first sound as mentioned in my comments in my code. When I click a button which should start another sound I get the following error:
03-16 23:07:38.478 13646-13646/com.example.cello.myownquiz E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException
at android.media.MediaPlayer.setDataSource(Native Method)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1005)
Is my MediaPlayer class okay or am I missing something depending on the state? Is this class the only spot to call release or do I have to put it somewhere in my activity, too?
Does anybody see my mistake? This problem with the mediaPlayer took me a whole day of trying, hope you can help me...
change mp.release(); to mp.reset();
public void reset ()
Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().
public void release ()
Releases resources associated with this MediaPlayer object. It is considered good practice to call this method when you're done using the MediaPlayer. In particular, whenever an Activity of an application is paused (its onPause() method is called), or stopped (its onStop() method is called), this method should be invoked to release the MediaPlayer object, unless the application has a special need to keep the object around. In addition to unnecessary resources (such as memory and instances of codecs) being held, failure to call this method immediately if a MediaPlayer object is no longer needed may also lead to continuous battery consumption for mobile devices, and playback failure for other applications if no multiple instances of the same codec are supported on a device. Even if multiple instances of the same codec are supported, some performance degradation may be expected when unnecessary multiple instances are used at the same time.
You need to keep the object around.
You can do it in a simple way
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(context, ringtone);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MEDIA);
mediaPlayer.prepare();
mediaPlayer.start();
me too i have this problem but i have used:
public void play(String name){
try {
AssetFileDescriptor afd = getAssets().openFd(name);
if(myPlayer == null){
myPlayer = new MediaPlayer();
}
myPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
myPlayer.prepare();
myPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
and to stop:
public void stopPlayer(){
if(myPlayer!= null && myPlayer.isPlaying()){
myPlayer.stop();
myPlayer = null;
}else{
myPlayer = null;
}
}
Related
I'm using MediaPlayer for playing sounds onClick. Until the sound is finished the click event is not play the sound again. How can it play the sound again on click, when the sound is currently playing?
final MediaPlayer mistake = MediaPlayer.create(getActivity(), R.raw.mistake);
tv_mistake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mistake.start();
}
});
You must create a new MediaPlayer object to play the sound again like so.
tv_mistake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mistake != null) {
mistake.release();
mistake = MediaPlayer.create(getActivity(), R.raw.mistake);
}
mistake.start();
}
});
You can read more about MediaPlayer in the following links.
Also a quite similar question
MediaPlayer, MediaPlayer Tutorial, MediaPlayer Tutorial From Google
Most of the errors in MediaPlayer comes due to improper handling of different states of its object.
You should release MediaPlayer object after completing playback or before calling start() again.
It is also recommended that once a MediaPlayer object is no longer being used, call release() immediately so that resources used by the internal player engine associated with the MediaPlayer object can be released immediately.
Create a MediaPlayer object as:
Mediaplayer mediaPlayer = null;
And call playMistakeSound() on button click:
tv_mistake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playMistakeSound()
}
});
Implement playMistakeSound() as:
void playMistakeSound() {
try {
// releases MediaPlayer object before calling create() again while previous is still playing
if (mediaPlayer != null){
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = MediaPlayer.create(getActivity() /*Context*/, R.raw.mistake);
// this will release MediaPlayer as soon as it completes
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (mp != null) {
mp.reset();
mp.release();
mediaPlayer = null;
}
}
});
mediaPlayer.start();
} catch (Exception e) {
// log exception and handle
e.printStackTrace();
}
}
I want a play button in my app that when clicked plays the audio and changes to pause, and when the pause button is clicked the audio stops and the button changes to play again and so on. But the button is not working as expected. Please help. I'm adding my java code below.
public class surah extends AppCompatActivity {
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_surah);
mp=MediaPlayer.create(surah.this, R.raw.surahkahf);
final ImageView audio = (ImageView)findViewById(R.id.btn);
audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()){
mp.stop();
audio.setBackgroundResource(R.drawable.play);
try {
mp.prepare();
}catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
mp.start();
audio.setImageResource(R.drawable.pause);
}
}
});
}
}
Use audio.setImageResource(R.drawable.play) instead of audio.setBackgroundResource(R.drawable.play). Use mp.pause() instead of mp.stop();
First, as aborocz mentions in comments, you probably intend to pause playback instead of stop it, so the method you want to use is pause(). In that case you would not need to prepare the MediaPlayer again, and it will start from the same place it was paused when playback is resumed.
Second, the isPlaying() method is not particularly appropriate for this purpose. There are race conditions that prevent the desired behavior. From the Android MediaPlayer documentation:
Note that the transition from the Started state to the Paused state
and vice versa happens asynchronously in the player engine. It may
take some time before the state is updated in calls to isPlaying(),
and it can be a number of seconds in the case of streamed content.
Instead, store your own boolean value.
public class surah extends AppCompatActivity {
private MediaPlayer mp;
private boolean isMediaPlaying = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_surah);
mp = MediaPlayer.create(surah.this, R.raw.surahkahf);
final ImageView audio = (ImageView)findViewById(R.id.btn);
audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isMediaPlaying) {
mp.pause();
audio.setBackgroundResource(R.drawable.play);
isMediaPlaying = false;
} else {
mp.start();
audio.setImageResource(R.drawable.pause);
isMediaPlaying = true;
}
}
});
}
}
I have a loop-all button and a stop button. Both buttons work fine while I'm still on the page. The problem is when I hit the loop-all button, it plays a series of audio files as it is supposed to, but when I leave the page (i.e. hit the phone's back button) and come back to the page, the audio doesn't stop! I hit the stop button, but it does nothing. The only way to stop it is to go into task manager and end the program. It seems to me that the reference of mp2 gets lost once I leave the page...Does anyone have any suggestions on how to fix this. Any help would be appreciated. Here is the code:
public class OneVoc extends ActionBarActivity {
private ListView lv;
private MediaPlayer mp;
private MediaPlayer mp2;
int[] myAudio = {R.raw.v_1100, R.raw.v_1101, R.raw.v_1102, R.raw.v_1103, R.raw.v_1104, R.raw.v_1105,
R.raw.v_1113, R.raw.v_1106, R.raw.v_1107, R.raw.v_1108, R.raw.v_1109, R.raw.v_1110, R.raw.v_1112,
R.raw.v_1114, R.raw.v_1115, R.raw.v_1116};
int mCompleted = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one_voc);
Button btnLoop = (Button) findViewById(R.id.button1);
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp2 != null) {
if (mp2.isPlaying()) {
mp2.setOnCompletionListener(null);
mp2.stop();
}
mp2.reset();
mp2.release();
mp2 = null;
}
}
});
btnLoop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mp2 = MediaPlayer.create(getBaseContext(), myAudio[0]);
mp2.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp2)
{
mCompleted++;
mp2.reset();
if (mCompleted < myAudio.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(myAudio[mCompleted]);
if (afd != null)
{
mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp2.prepare();
mp2.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted == myAudio.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(myAudio[mCompleted]);
if (afd != null)
{
mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp2.prepare();
mp2.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp2.release();
mp2 = null;
}
}
});
mp2.start();
}
});
try overriding onbackpressed method
#Override
public void onBackPressed()
{
// code here to stop and finish()
super.onBackPressed();
}
I think it's an It's an Audio buffer issue, memory is loaded in audio buffer and persist later on,finish() might not help u.
When u press back button on an android button it simply calls the finish() for current activity, while when u press home button it calls onPause(),
You need to override onBackPressed() method, and before line super.onbackPressed();
Put your code to stop playing.
When u go to TakMgr it simply get's the PID refer to ur App process and kills the process.
Which is like System.exit(0); or android.os.process.kill(getMyPid());
Which simply ends ur app which u do not want.
Can you pause your mp in onPause() and restart it in onResume()?
Maybe you want also to store in savedInstance at which point you were!
Hope it's helpful
when you back press the activity just stop the mediaplayer and free the resources and finish the activity.that's it..!
#Override
public void onBackPressed()
{
btnStop.performClick();
super.onBackPressed();
}
I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second time. That part works fine now here is the problem, when I click again on button to play sound again, it doesn't play it, Media player is completely stopped. I was looking on forums but I can't seem to find an answer that could help me.
Here is my Activity:
MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
final MediaPlayer mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
mpButtonClick1.reset();
}
else {
mpButtonClick1.start();
}
}
});
When I try to write mpButtonClick1.prepare(); I get error Unhandled Exception Type IOE exception
Try to use pause instead of stop.
Reason: if you pause the MediaPlayer, then you can resume it later. However, if you use stop, almost any other method won't work and you will have to prepare the MediaPlayer again (or create a new one).
More info: here and here
PS: don't forget to release the memory when you finish using the resources.
Try this:
You should use only one mediaplayer object
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Change your class with below code:
remove reset();.
init well all components:
MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
}
else {
mpButtonClick1.start();
}
}
});
You're calling mpButtonClick1.reset() after mpButtonClick1.stop() - don't do that:
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
mpButtonClick1.reset(); //<--------- calling reset(), remove this line
}
The docs for reset() say:
Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().
Remove mpButtonClick1.reset() and it should work.
Keep in mind that MediaPlayer works as a state machine, which means that if you call methods in the wrong order, you'll get problems. Please read about MediaPlayer here and here.
Hey please use following
for stop -> media player
mp.seekTo(0);
mp.pause();
again for start just call
mp.start();
In my experience when I need to play multiple times and I may need to stop one play to start another play, (like in the case of multiple buttons), I just create another player, making sure that I release the resources for the previous one. To stop just use
mediaPlayer.stop();
But for play use something like this (adapt the logging to your specific needs) to create/recreate your player:
private boolean createMediaPlayer()
{
if (mediaPlayer!=null)
{
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer=null;
}
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setVolume(1f, 1f);
try
{
mediaPlayer.setAudioStreamType(Interop.PRIMARY_STREAM);
mediaPlayer.setDataSource(m_soundFile);
mediaPlayer.prepare();
return true;
// Interop.logDebug(TAG + "-loadAudio: SUCCESS" + m_soundFile);
} catch (Exception e)
{
Interop.logError(TAG + "-LoadAudio for Clic Sound: audioPlayer prepare failed for current file: " + m_soundFile);
Interop.logError(TAG + "-Exception: " , e);
return false;
}
}
and than use
if (createMediaPlayer())
mediaPlayer.start();
this will ensure proper release of the resources used by the media player.
A simple solution is to Use pause instead of stop and the seek to the beginning of the song.
I know that this question is quite old but recently while learning Android, I also got stuck at this point and found a very simple solution which I'd like to share with everyone.
Instead of trying to stop or reset the media, you can just seek back to the starting position.
mediaPlayer.seekTo(0);
For reference, I am also posting my code below:
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
public void play(View view) {
mp.start();
}
public void pause(View view) {
mp.pause();
}
public void stop(View view) {
// this seeks to the beginning of the file
mp.seekTo(0);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.sample_audio);
}
}
I Have created a branch activity .Now i wanted to add two button on that branch activity.
When i click on 'sound on' button then my beep sound on start and when i clicked on 'sound off' then my beep sound off. and also they hide simultaneously.
Thank's
MY Code on Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sound_layout);
soundBttnOn =(Button) findViewById(R.id.soundBttnOn);
soundBttnOn.setOnClickListener(
new OnClickListener(){
#Override
public void onClick(View v) {
startMediaPlayer();
}
}
);
soundBttnoff =(Button) findViewById(R.id.soundBttnOff);
soundBttnoff.setOnClickListener(
new OnClickListener(){
#Override
public void onClick(View v) {
stopMediaPlayer();
}
}
);
}
private void startMediaPlayer() {
mediaPlayer = MediaPlayer.create(SoundLayout.this,R.raw.keybutton5);
mediaPlayer.start();
}
private void stopMediaPlayer() {
if( mediaPlayer != null ) {
MediaPlayer mp = null;
mp.stop();
mp.release();
}
}
It showing no problem but it is not working too..:P..I am not able to implement sound.
You can do simple google search to find tons of samples for adding button. However for playing sound file check out the MediaPlayer class.
Button startBtn, stopBtn;
//get the reference of Button
....
final MediaPlayer mp = new MediaPlayer();
startBtn.onClickListener() {
public void onClick(View v) {
try {
mp.setDataSource(path+"/"+audio.mp3);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
};
stopBtn.onClickListener() {
public void onClick(View v) {
if(mp.isPlaying()) {
mp.stop();
//hide buttons
stopBtn.setVisibiltiy(View.GONE);
startBtn.setVisibility(View.GONE);
}
}
};
PS: For only on and off, you don't need two buttons, you could do with one button.
EDIT:
For single button, just use the playing state of Media player for deciding about the action to take on button click.
singleBtn.onClickListener() {
public void onClick(View v) {
try {
if(mp.isPlaying()) mp.stop();
else {
mp.setDataSource(path+"/"+audio.mp3);
mp.prepare();
mp.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};