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");
}
Related
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 :)
When i click a imgniatp at the display, audio play very well, but if i click imgbukap too, before audio of imgniatp finish, imgbukap also play audio. so both audio play together. How to play one sound at a time?
package sodik.com.ramadhan;
import sodik.com.ramadhan.R;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.TextView;
public class Puasa3Activity extends Activity implements OnClickListener{
MediaPlayer mp;
ImageButton imgniatp1, imgbukap2;
String p1, p2, p3, p4, p5, p6, p7, p8, p9;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.puasa3);
TextView p1tk = (TextView) findViewById(R.id.p1tk);
TextView p2tk = (TextView) findViewById(R.id.p2tk);
imgniatp1=(ImageButton) findViewById(R.id.imgniatp);
imgniatp1.setOnClickListener(this);
imgbukap2=(ImageButton) findViewById(R.id.imgbukap);
imgbukap2.setOnClickListener(this);
}
public void onClick(View v){
switch (v.getId()){
case R.id.imgniatp:
mp= MediaPlayer.create(this, R.raw.bukapuasa);
mp.setVolume(1,1);
mp.start();
Toast.makeText(this, " Memainkan Buka Puasa", Toast.LENGTH_SHORT).show();
break;
case R.id.imgbukap:
mp = MediaPlayer.create(this, R.raw.niatpuasa);
mp.setVolume(1,1);
mp.start();
Toast.makeText(this, " Mainkan Niat Puasa ", Toast.LENGTH_SHORT).show();
break;
}
}
`
You could check to see if the MediaPlayer is already playing something, and start the clip in an onCompletionListener if it is
if(mp != null && mp.isPlaying()) {
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp = MediaPlayer.create(this,R.raw.bukapuasa);
mp.start();
}
});
} else {
mp = MediaPlayer.create(this,R.raw.bukapuasa);
mp.start();
}
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();
}
});
i use these lines to play some audio file with mediaplayer, both on a service and in an activity, yet there is no sound on my device, what could be the reason? and what should i try to do to understand whats wrong and finally fix that?
MediaPlayer mp = MediaPlayer.create(this, R.raw.alert);
mp.start();
Intent viewMediaIntent = new Intent();
viewMediaIntent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(objectFilePath);
viewMediaIntent.setDataAndType(Uri.fromFile(file), "audio/*");
viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(viewMediaIntent);
http://developer.android.com/reference/android/media/MediaPlayer.html
Check out the state diagram in the MediaPlayer docs.
After you've created the MediaPlayer it is in the Idle state. As you can see, you need to initialize and prepare it before you call start().
Check the following code, it works fine for me. I hope it will work for you also.....Dont forget to add Audio PlayBack permission in android Manifest File
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://android.erkutaras.com/media/audio.mp3";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}
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.