MediaPlayer stops playing the sounds - Android - android

Here is a simple piano app and it works but there is a problem. After about 20 clicks (sometimes it is exactly 28 clicks) even I click the buttons it doesn't play any sound. The app doesnt crash or doesn't warn me about anything. It is just nothing . There is no sound. Do you have any idea?
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;
}
}

Looks like you're creating a new MediaPlayer instance to play each sound. You should either reuse them or clean them up.
From the documentation of the MediaPlayer.create() method:
Convenience method to create a MediaPlayer for a given resource id. On
success, prepare() will already have been called and must not be
called again.
When done with the MediaPlayer, you should call release(), to free the
resources. If not released, too many MediaPlayer instances will result
in an exception.

simple way is to add onComplationListener
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer p1) {
p1.release();
}
});

Related

MediaPlayer will not stop or pause

I am trying to make a simple app to help me learn how to code for Android. The apps principle is simply this: When you press down on a button it starts playing a sound file. When you release the button, the audio stops. Pressing down on the button works, but releasing it does not. Thanks in advance! Here is my java code:
package com.example.siriu.presstoplay;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.MotionEvent;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.pressbutton);
button.setOnTouchListener(handleTouch);
mp = MediaPlayer.create(this, R.raw.test);
}
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("button", "down");
play();
break;
case MotionEvent.ACTION_UP:
Log.d("button", "up");
pause();
break;
}
return true;
}
};
public void play (){
final MediaPlayer mp = MediaPlayer.create(this, R.raw.test);
mp.start();
Log.d("MediaPlayer", "started");
}
public void pause (){
mp.stop();
Log.d("MediaPlayer", "paused");
}
}
Android MediaPlayer will not stop or pause
Because in your play () method you are starting local declared MediaPlayer of play () method
and in your pause () you are trying to stop MediaPlayer that you have declared global
in this situation your global declared MediaPlayer mp; hasn't start yet
Try this
Remove final MediaPlayer mp = MediaPlayer.create(this, R.raw.test); from Your play() Method
public void play (){
mp.start();
Log.d("MediaPlayer", "started");
}

Can anyone deal with it?

I would like my button (should it be a button or sth else?) to to play music when I hover on it and stop at HOVER_EXIT. What should I implement for
case MotionEvent.ACTION_HOVER_MOVE: to make button play music still, without pauses from ENTER to EXIT and on MOVE dont do anything?
There is also an error - when I try to open a screen with this hoverbutton, app crashes and turns off.
Here is my java code:
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class DisplayActivity extends AppCompatActivity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
b1 = (Button)findViewById(R.id.button1);
b1.setOnHoverListener(new View.OnHoverListener()
{
#Override
public boolean onHover(View v, MotionEvent event) {
MediaPlayer player=MediaPlayer.create(DisplayActivity.this,R.raw.sound);
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_ENTER:
player.start();
break;
case MotionEvent.ACTION_HOVER_EXIT:
player.stop();
break;
}
return true;
}
});}`
public class DisplayActivity extends AppCompatActivity {
private MediaPlayer player;
#Override
protected void onResume() {
super.onResume();
// create media player only when required
player = MediaPlayer.create(this, R.raw.sound);
// this will keep the audio playing, even if you hover for long time
player.setLooping(true);
}
#Override
protected void onPause() {
super.onPause();
// release is as soon as possible
player.release();
player = null;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
findViewById(R.id.button1).setOnHoverListener(new View.OnHoverListener() {
#Override
public boolean onHover(
View v,
MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_ENTER:
player.start();
break;
case MotionEvent.ACTION_HOVER_EXIT:
// if you choose to stop the player, you need to prepare it again by calling player.prepare(); before restarting it.
// I chose to pause it and seek it back to beginning
player.pause();
player.seekTo(0);
break;
}
return true;
}
});
}
}
Hope this helps :)

Continue playing music when screen orientation is changed in Android

I have a problem where I can't keep the music playing when chaning the screen orientation in my program. I tried adding android:configChanges="keyboardHidden|orientation|screenSize inside the MainActivity in the AndroidManifest.xml file, but although it keeps the music playing, it also disables the different layout for the landscape mode.
Here is the code for the MainActivity:
package com.example.gomoku;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up click listeners for all the buttons.
View newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(this);
View highScoreButton = findViewById(R.id.high_score_button);
highScoreButton.setOnClickListener(this);
View aboutButton = findViewById(R.id.about_button);
aboutButton.setOnClickListener(this);
View exitButton = findViewById(R.id.exit_button);
exitButton.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.new_button:
startGame();
break;
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
case R.id.exit_button:
finish();
break;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(this, Prefs.class));
return true;
}
return false;
}
#Override
protected void onResume() {
super.onResume();
Music.play(this, R.raw.main);
}
#Override
protected void onPause() {
super.onPause();
Music.stop(this);
}
private void startGame() {
Intent intent = new Intent(MainActivity.this, Game.class);
startActivity(intent);
}
}
And here is the code for Music:
package com.example.gomoku;
import android.content.Context;
import android.media.MediaPlayer;
public class Music {
private static MediaPlayer mp = null;
/** Stop old song and start new one. */
public static void play(Context context, int resource) {
stop(context);
// Start music only if not disabled in preferences.
if (Prefs.getMusic(context)) {
mp = MediaPlayer.create(context, resource);
mp.setLooping(true);
mp.start();
}
}
/** Stop the music. */
public static void stop(Context context) {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Editing the original code;
package com.example.gomoku;
import android.content.Context;
import android.media.MediaPlayer;
public class Music {
//####First change is here####
//adding a variable to store the time of music being played.
private static int pos = 0;
private static MediaPlayer mp = null;
/** Stop old song and start new one. */
public static void play(Context context, int resource) {
stop(context);
// Start music only if not disabled in preferences.
if (Prefs.getMusic(context)) {
mp = MediaPlayer.create(context, resource);
mp.setLooping(true);
mp.start();
//####Second change is here####
//this will continue the music from wherever it was paused
mp.seekTo(pos);
}
}
/** Stop the music. */
public static void stop(Context context) {
if (mp != null) {
//####Third change is here####
mp.pause();//to pause the music
//to store current pause time in pos
//as pos is static it will retain the value
pos = mp.getCurrentPosition();
mp.stop();
mp.release();
mp = null;
}
}
}
add this code to stop the app when back key is pressed.
#Override
public void onBackPressed() {
pos = 0;
super.onBackPressed();
mp.release();
System.exit(0);
}
Now this app will:
Play music in loop when it starts.
Continue the music when screen orientation is changed.
Resume music when app is restarted after pressing home button.
Restart song if the back button was pressed.

New to app development. Creating a button that links one class to another?

I have created two classes. I want to have a button on class 1 (MainActivity) that when it is pressed, it will take me to class 2 (Alphabet). I have tried numerous ways of doing it and I have been unsuccessful. Here is my original code below. Can anyone help me?
Sorry, I am new to app developing.
package com.example.lullabymain;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// new code
setVolumeControlStream(AudioManager.STREAM_MUSIC);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
}
public void onClick(View v) {
int resId = 0;
switch (v.getId()) {
case R.id.button1: resId = R.raw.rockabye; break;
case R.id.button2: resId = R.raw.hushlittlebaby; break;
case R.id.button3: resId = R.raw.twinkle; break;
case R.id.button4: resId = R.raw.hickory; break;
case R.id.button5: resId = R.raw.oldmcd; break;
}
//release any resources from previous mediaplayer
if (mp != null) {
mp.release();
}
//create a new mediaplayer to play this sound
mp = MediaPlayer.create(this, resId);
mp.start();
}
#Override
protected void onStop()
{
//stop audio
super.onStop();
mp.stop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The code below is the code that I attempted which includes 'Intent'
package com.example.lullabymain;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// new code
**View button6 = findViewById(R.id.button6);
button6.setOnClickListener(this);**
setVolumeControlStream(AudioManager.STREAM_MUSIC);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
}
public void onClick(View v) {
int resId = 0;
switch (v.getId()) {
case R.id.button1: resId = R.raw.rockabye; break;
case R.id.button2: resId = R.raw.hushlittlebaby; break;
case R.id.button3: resId = R.raw.twinkle; break;
case R.id.button4: resId = R.raw.hickory; break;
case R.id.button5: resId = R.raw.oldmcd; break;
**case R.id.button6:
Intent i = new Intent(this, Alphabet.class);
startActivity(i);
break;**
}
//release any resources from previous mediaplayer
if (mp != null) {
mp.release();
}
//create a new mediaplayer to play this sound
mp = MediaPlayer.create(this, resId);
mp.start();
}
#Override
protected void onStop()
{
//stop audio
super.onStop();
mp.stop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
If you want to do custom coding, you need to learn langauges like Objective-C or Swift to develop iOS app. Or another way is mobile app development platform. With the help of app development tools you can develop apps with drag & Drop facilities without writing a single line of code.
I am an iOS app developer, I have tried most of the mobile app development platforms. I have developed more than 50 apps till today with the help of Phonegap, Telerik, Configure.IT etc. They are running successfully on app store.
As per my experience in this field, I recommend developers as well as beginners to use mobile app development platform like http://www.configure.it/, because it provides automatic coding, app preview facility, direct API connect and a lot more features. These things save a lot more development time and provides fast and well designed app in much less time.
The main benefit of this tool, it is web based platform so you do not require to buy Mac system, you can make an app from any place as well as from any system.
Currently in MainActivity Activity you are not adding setOnClickListener to button6 but in onClick method you are trying to start Activity on button6 click . to get your code working add setOnClickListener to button6 also as
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
Button button6 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// new code
button6 = (Button)findViewById(R.id.button6);
button6.setOnClickListener(this);
and register Alphabet Activity in Manifest as :
<activity android:name=".Alphabet" />
package com.example.lullabymain;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// new code
Button button6 = (Button)findViewById(R.id.button6);
button6.setOnClickListener(this);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
}
public void onClick(View v) {
int resId = 0;
switch (v.getId()) {
case R.id.button1: resId = R.raw.rockabye; break;
case R.id.button2: resId = R.raw.hushlittlebaby; break;
case R.id.button3: resId = R.raw.twinkle; break;
case R.id.button4: resId = R.raw.hickory; break;
case R.id.button5: resId = R.raw.oldmcd; break;
case R.id.button6:
Intent i = new Intent(getApplicationContext(), com.example.lullabymain.Alphabet.class);
startActivity(i);
break;
}
//release any resources from previous mediaplayer
if (mp != null) {
mp.release();
}
//create a new mediaplayer to play this sound
mp = MediaPlayer.create(this, resId);
mp.start();
}
#Override
protected void onStop()
{
//stop audio
super.onStop();
mp.stop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
When you set the context of {this} you are using the {this} of the onClickListener. use getApplicationContext();
Button button6 = (Button)findViewById(R.id.button6);
button6.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startActivity(new Intent(getApplicationContext(), Alphabet.class));
}
});
What are the errors that your code is throwing?
What you need to do is set on click listeners on the required buttons
and followed by Intents to go to your new class for example
Intent i5 = new Intent(this, HadithList.class);
startActivity(i5);

MediaPlayer and map issues android app (noob question)

I'm just learning here. I'm trying to make a soundboard with around forty sounds, but I'm having some trouble how to get it to work using a maphash. Can anyone save me?
--------------soundboard-------------------------
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import java.util.HashMap;
import java.util.Map;
public class main extends Activity {
MediaPlayer mp=null;
\\\if I put put "MediaPlayer mp;" here it only plays one sound\\\
ImageButton Button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(R.id.button1, R.raw.sound1);
map.put(R.id.button2, R.raw.sound2);
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
mp = MediaPlayer.create(this, entry.getValue());
\\\if I put "final MediaPlayer mp = MediaPlayer.create(this, entry.getValue());" here I cant stop MediaPlayer with onpause and onstop overrides.\\\
ImageButton button = (ImageButton) findViewById(entry.getKey());
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}
});
}
}
#Override
protected void onStop() {
super.onStop();
if(mp.isPlaying()){
mp.stop();
mp.release();
}
}
#Override
public void onDestroy(){
super.onDestroy();
mp.release();
}
}
As I suggested in your previous question, don't create all those mediaplayer instances, for two reasons:
You lose all instances and have only the last one. always.
The onCreate() become very long method for no reason.
instead, remove mp = MediaPlayer.create(this, entry.getValue()); from your for loop, and move it to inside of your listener, something like that (not tested...):
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int sound = map.get(v.getId());
mp = MediaPlayer.create(main.this, sound);
mp.start();
}
});
So you would create the mediaplayer instance only when needed.
BTW, main is not a good name for a class.

Categories

Resources