I'm using MediaPlayer for play a click sound when user clicks on a button. Sometimes the sound will play fine but other times it is too slow. For example first click is fine but second click is too slow.
Here is my code:
private MediaPlayer mClickSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mClickSound = MediaPlayer.create(this, R.raw.click);
}
#Override
public void onClick(View view) {
try {
if (mClickSound.isPlaying()) {
mClickSound.stop();
mClickSound.release();
mClickSound = MediaPlayer.create(this, R.raw.click);
}
mClickSound.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Try this:
mClickSound.reset();
AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.click);
if (afd == null) return;
mClickSound.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mClickSound.start();
afd.close();
setDataSource is taken from here:
https://stackoverflow.com/a/20111291/6159609
The reset method is supposed to be faster.
Please try below code working fine for me...
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
Button btn;
MediaPlayer mClickSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
mClickSound = MediaPlayer.create(this, R.raw.click);
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickSound.isPlaying()) {
mClickSound.reset();
}
else {
mClickSound = MediaPlayer.create(this, R.raw.click);
mClickSound.start();
}
}
}
Related
I am trying to get the Image Button to play a sound each time it's clicked. For example, if the sound is playing for few seconds and I press the button again it should start from the beginning. I managed to get the sound working but it's not repeating it. How can I get it to start over?
ImageButton bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (ImageButton) findViewById(R.id.clickme);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bird);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
}
Try this:
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.bird);
}
mp.start();
} catch(Exception e) {
e.printStackTrace();
}
}
Use MediaPlayer.seekto() to seek to the start of the audio file.
ImageButton bt;
private MediaPlayer mp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (ImageButton) findViewById(R.id.clickme);
mp = MediaPlayer.create(this, R.raw.bird);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()) {
mp.seekTo(0);
} else {
mp.start();
}
}
});
}
i am very new in "coding" for Googles Android.
At the moment i am programming a small app with one button. If you click on it, it plays a random sound. BUT :D ... it plays a sound, on every start an other. But no random sounds if you press the button often.
I dont know where is my mistake.
Here is the code (don't laugh!):
public class MainActivity extends Activity {
//MediaPlayer
MediaPlayer mp;
ImageButton soundbutton;
//Sounds
int[] sounds={R.raw.s1, R.raw.s2, R.raw.s3, R.raw.s4, R.raw.s5, R.raw.s6, R.raw.s7, R.raw.s8, R.raw.s9, R.raw.s10};
Random r = new Random();
int Low = 0;
int High = 10;
int rndm = r.nextInt(High-Low) + Low;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
//MediaPlayer
soundbutton = (ImageButton)this.findViewById(R.id.randomsoundbutton89);
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
soundbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
}
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Help! (from Germany)!
Use this code to get different sound
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
//MediaPlayer
soundbutton = (ImageButton)this.findViewById(R.id.randomsoundbutton89);
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
soundbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
rndm = r.nextInt(High-Low) + Low;
mp = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
}
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Media Player is starting and playing stream fine. But if I press stop once, I cannot play that again. App is closed. Code is here
Button StartStop;
final MediaPlayer MyRadio = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StartStop = (Button) findViewById(R.id.StartStop);
StartStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (MyRadio.isPlaying()){
MyRadio.stop();
MyRadio.release();
StartStop.setText("Start");
} else {
PrepareRadio("http://220.247.162.146:7170/");
MyRadio.start();
StartStop.setText("Stop");
}
}
});
}
public void PrepareRadio(String Source){
try {
MyRadio.reset();
MyRadio.setDataSource(Source);
MyRadio.prepare();
} catch (Exception e) {
e.printStackTrace();
}
}
I need your advice to solve this.
Initialize your MediaPlayer class on onCreate() method.
final MediaPlayer MyRadio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyRadio = new MediaPlayer();
}
Move MyRadio.release(); and put it in onDestroy in your Activity
I think this is a decent way to use MediaPlayer for a Button or one time use. Am I right? Is the try block necessary? And what should I be trying to catch here? I'm really having a hard time finding a rock solid way to play a sound once.
// Button sound
private void playButtonSound() {
try{
final MediaPlayer startPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.sound);
startPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
startPlayer.release();
}
});
startPlayer.start();
} catch(Throwable t){}
}
I use it like that:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.tosse);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
I am new to Android, my requirement is to use only one button for playing and pause using media player class?
Once you have your MediaPlayer set up, I would just set up in your onCreate() and onResume() methods, a check to see if the MediaPlayer is currently playing (MediaPlayer's isPlaying() method should work for you), and if it is playing, set the button's image and click handler to change it to a pause button. If the MediaPlayer isn't playing, then set it to be a play button.
You'll also need to handle listening for events such as when the MediaPlayer stops (finishes playing the audio file), as well as inverting the button state when you press it (i.e. pressing play changes button to pause, and vice versa).
I would use 2 buttons and hide one of them:
public class MyActivity extends Activity implements View.OnClickListener {
Button playBtn;
Button pauseBtn;
public void onCreate() {
playBtn = (Button) findViewById(R.id.playButton);
pauseBtn = (Button) findViewById(R.id.pauseButton);
playBtn.setOnClickListener(this);
pauseBtn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.playButton:
// play music here
playBtn.setVisibility(Button.GONE);
pauseBtn.setVisibility(Button.VISIBLE);
break;
case R.id.pauseButton:
// pause music here
pauseBtn.setVisibility(Button.GONE);
playBtn.setVisibility(Button.VISIBLE);
break;
}
}
}
you can use a single Imagebutton and change the drawable image , in conjuction with a toggling boolean variable to check the state of the button (play/pause).
This is how I implemented it
ImageButton playButton;
private boolean playOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// some code here
playButton = (ImageButton)findViewById(R.id.btn_play);
//other specifications and your code
}
public void play(View view){
myplayfunction();
}
public void myplayfunction(){
if (playOn){
playOn=false;
playButton.setImageResource(R.drawable.icn_pause);
//your mediaplayer functions
}else{
playOn=true;
playButton.setImageResource(R.drawable.icn_play);
//pause the mediaplayer
}
}
Also, don't forget to toggle your imagebutton at the end, onCompletionListener() method of the mediaplayer
The following code worked for me. The value of the "playedLength" variable should also be initialize to zero, and set the "mediaPlaying" boolean value to false in the media player stop function to avoid errors.
public class MainActivity extends AppCompatActivity {
private Button btnPlay;
private MediaPlayer mPlayer;
private String mFileName = null;
private int playedLength; //variable for the CurrentPosition of audio when paused
private boolean mediaPlaying; // boolean variable for toggling play, pause and resume actions
// some custom codes for my app...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// some custom codes for my app.....
btnPlay = (Button) findViewById(R.id.button_play);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlaying){
mediaPlaying = false;
//pause the media player
mPlayer.pause();
playedLength = mPlayer.getCurrentPosition();
btnPlay.setBackgroundResource(R.mipmap.ic_pause_focused_background);
}else{
mediaPlaying = true;
if(mPlayer == null){
// create the media player
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
btnPlay.setBackgroundResource(R.mipmap.ic_play_focused_background);
} else
// resume playing
mPlayer.seekTo(playedLength);
mPlayer.start();
btnPlay.setBackgroundResource(R.mipmap.ic_play_focused_background);
}
}
});
}
final Button bPlay = (Button)findViewById(R.id.bPlay);
MediaPlayer song1 = MediaPlayer.create(tutorialFour.this, R.raw.fluet);
Button bStop = (Button)findViewById(R.id.bStop);
bPlay.setWidth(10);
song1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
bPlay.setText("Play");
}
});
bPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
b=true;
if(bPlay.getText().equals("Play") && b==true)
{
song1.start();
bPlay.setText("Pause");
b=false;
}
else if(bPlay.getText().equals("Pause"))
{
x=song1.getCurrentPosition();
song1.pause();
bPlay.setText("Resume");
Log.v("log",""+x);
b=false;
}
else if(bPlay.getText().equals("Resume") && b==true)
{
song1.seekTo(x);
song1.start();
bPlay.setText("Pause");
b=false;
}
}
});
Button
android:id="#+id/buttonPlay"
android:onClick="Play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="160dp"
android:layout_marginTop="243dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="100dp"
android:text="#string/play"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
//-----------------------------------------------------------------------
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
boolean isPlaing = true;
Button buttonPlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = findViewById(R.id.buttonPlay);
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.stuff);
}
public void Play(View view) {
if(isPlaing) {
mediaPlayer.start();
buttonPlay.setText("Pause");
isPlaing = false;
}else {
mediaPlayer.pause();
buttonPlay.setText("Play");
isPlaing = true;
}
}
}