I built a small app which basically vibrates and plays an mp3 file on checking a checkbox, but somehow the music won't stop after unchecking the checkbox:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Vibrator vibrator = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
final CheckBox vibrateBoxStrong = (CheckBox) findViewById(R.id.checkPowerStrong);
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
vibrator.vibrate(1000);
handler.postDelayed(this, 1000);
}
};
vibrateBoxStrong.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.fansound1);
if(vibrateBoxStrong.isChecked()) {
handler.postDelayed(r, 100);
mediaPlayer.start();
} else {
mediaPlayer.stop();
handler.removeCallbacks(r);
vibrator.cancel();
}
}
}
);
}
}
For Playing mp3
MediaPlayer mPlayer = MediaPlayer.create(context, R.raw.aaanicholas);
to start
mPlayer.start();
to stop
mPlayer.stop();
In your case use
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Vibrator vibrator = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
MediaPlayer mPlayer = MediaPlayer.create(context, R.raw.aaanicholas);
Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
final CheckBox vibrateBoxStrong = (CheckBox) findViewById(R.id.checkPowerStrong);
vibrateBoxStrong.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.fansound1);
if(vibrateBoxStrong.isChecked()) {
v.vibrate(1000); // it will vibrate for 1000 milliseconds
mPlayer.start();
} else {
mPlayer.stop();
vibrator.cancel();
}
}
}
);
}
}
Related
public class Options extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music01);
}
public void playSong(View view) {
CheckBox musicCheck = findViewById(R.id.musicCheck);
if (musicCheck.isChecked()) {
mediaPlayer.start();
}
else {
mediaPlayer.stop();
}
}
}
When I check the checkbox, the music starts playing and when I uncheck the checkbox, the music stops playing. However, when I check the checkbox again the music does not play.
Add this in onCreate
musicCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (musicCheck.isChecked()) {
mediaPlayer.start();
} else {
mediaPlayer.stop();
}
}
});
I have a toggle button and i need the 'mp' sound to play every second if that button is toggled.The code below is what i tried and it does play the sound every second but the button stops responding so i can't turn it off.
ToggleButton btn = findViewById(R.id.button);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.beat);
btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
while (isChecked) {
mp.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thank you in advance.
Never use Thread.sleep(1000) it is the terrible thing you can do to the app. Your app is not
responsding because you are putting Main thread of app to sleep.
I have created this class for you for desmonstration. you can tweak is further to your needs.
private Handler soundHandler = new Handler();
private int delay = 1000;
private Runnable soundRunnable;
private MediaPlayer mediaPlayer;
private boolean isToggleChecked;
#Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton toggleButton = findViewById(R.id.button);
mediaPlayer = MediaPlayer.create(this, R.raw.beat);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked){
isToggleChecked = isChecked;
if(isChecked){
playSound();
}else {
stopSound();
}
}
});
}
#Override protected void onResume(){
super.onResume();
if(isToggleChecked){
playSound();
}
}
// this will make sure sound stops when app stops or goes in background
#Override
protected void onPause() {
soundHandler.removeCallbacks(soundRunnable);
super.onPause();
}
private void playSound(){
soundHandler.postDelayed(new Runnable() {
public void run() {
soundRunnable = this;
if(mediaPlayer != null) {
mediaPlayer.start();
}
soundHandler.postDelayed(soundRunnable, delay);
}
}, delay);
}
private void stopSound(){
if(mediaPlayer != null){
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
soundHandler.removeCallbacks(soundRunnable);
}
}
}
I found an answer to another question and modified it to fit my needs and now it works perfectly.Here is the solution/code.
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer = null;
int delayMillis;
Handler handler;
Runnable runnable;
private boolean isToggleChecked;
private ToggleButton toggleButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = findViewById(R.id.button);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
};
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
isToggleChecked = true;
toggleMediaPlayer();
}
else {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
handler.removeCallbacks(runnable);
isToggleChecked = false;
}
}
});
}
#Override
public void onResume() {
super.onResume();
if (isToggleChecked) {
toggleButton.setChecked(true);
}
else {
toggleButton.setChecked(false);
}
}
private void toggleMediaPlayer(){
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
handler.removeCallbacks(runnable);
}else{
mediaPlayer = MediaPlayer.create(this, R.raw.beat);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
delayMillis = 1000;
handler.postDelayed(runnable,delayMillis);
}
});
}
}
}
I have two buttons and two songs. If I click the first button, the first sound plays. But if I click the second button while the first sound is playing the second sound starts playing too.
How can I stop other sounds?
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer johnCenaPlayer = MediaPlayer.create(this, R.raw.john_cena);
Button johnCenaButton = (Button) findViewById(R.id.john_cena_button);
johnCenaButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
johnCenaPlayer.start();
}
});
final MediaPlayer haGayPlayer = MediaPlayer.create(this, R.id.ha_gay_button);
Button haGayButton = (Button) findViewById(R.id.ha_gay_button);
haGayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
haGayPlayer.start();
}
});
}
Stop the other MediaPlayer in clickListener using stop() method.
public void onClick(View view) {
ha_gay.stop()
john_cena.start();
}
If you have many audio files use a single MediaPlayer and change the sources dynamically.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mediaPlayer = new MediaPlayer();
Button john_cena_button = (Button) findViewById(R.id.john_cena_button);
john_cena_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopAndPlay(R.raw.john_cena, mediaPlayer);
}
});
Button ha_gay_button = (Button) findViewById(R.id.ha_gay_button);
ha_gay_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopAndPlay(R.raw.ha_gay, mediaPlayer);
}
});
}
// This resets the mediaPlayer and starts the given audio
private void stopAndPlay(int rawId, MediaPlayer mediaPlayer) {
mediaPlayer.reset();
AssetFileDescriptor afd = this.getResources().openRawResourceFd(rawId);
try {
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
Try this one. Do it same for the other.
final MediaPlayer john_cena = MediaPlayer.create(this, R.raw.john_cena);
Button john_cena_button = (Button) findViewById(R.id.john_cena_button);
john_cena_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (he_gay.isPlaying()){
he_gay.stop();
}
else if (john_cena.isPlaying()){
john_cena.seekTo(0);
} else{
john_cena.start();
}
}
});
i'm the newbie this my code
the sound is not play but when i click the button the toast is show
anyone help me??
public class DB_Parse extends Activity {
MediaPlayer mp;
Button button;
int ,sound;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.keterangan);
final int sound = iIdentifikasi.getIntExtra("dataID", 0);
button=(Button)findViewById(R.id.btnsound);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (sound==1){
mp = MediaPlayer.create(getApplicationContext(), R.raw.munfasil);
mp.start();
}
Toast.makeText(getApplicationContext(),
"Sound is Play", Toast.LENGTH_LONG).show();
}
});
}
}
if (sound==1) 1 from _id in sqlite
try this way it will work
public class DB_Parse extends Activity {
private static final String TAG = "MyActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG, "Initializing sounds...");
final MediaPlayer mp = MediaPlayer.create(this, R.raw.youraudio);
Button play_button = (Button)this.findViewById(R.id.play_button);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Playing sound...");
mp.start();
}
});
Log.v(TAG, "Sounds initialized.");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Put your audio/media file in asset folder instead putting into raw folder and follow above snippet, its working quite fine for me..
try
{
AssetFileDescriptor afd = getAssets().openFd("your_media_file_name.mp3");
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
}
catch(Exception e)
{ e.printStackTrace();}
Fire it on your button click event
First of all you are declaring your variable sound twice.
Please change:
final int sound = iIdentifikasi.getIntExtra("dataID", 0);
for
sound = iIdentifikasi.getIntExtra("dataID", 0);
The other thing that you should try is changing the toast inside your if, so you are sure that sound is 1.
if (sound==1){
mp = MediaPlayer.create(getApplicationContext(), R.raw.munfasil);
mp.start();
Toast.makeText(getApplicationContext(),
"Sound is Play", Toast.LENGTH_LONG).show();
}
If toast is not displaying your int sound is not 1.
I want to develop media player type of application which has two button one for play and pause and one for stop. I take two image buttons in my layout file and reference it in Java file and code like this which I put here, but when I click on stop button audio is getting stopped but then I want replay audio file; but I cant play with play button.
my Java code below
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_aarti_fragment, container, false);
btnplay=(ImageButton)v.findViewById(R.id.btnplay);
btnstop=(ImageButton)v.findViewById(R.id.btnstop);
seekbar=(SeekBar)v.findViewById(R.id.seekbar);
mp = MediaPlayer.create(getActivity(), R.raw.arti);
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Pause",Toast.LENGTH_SHORT).show();
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
Use This:
private BackgroundSound mBackgroundSound;
private MediaPlayer player;
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
player = MediaPlayer.create(HomePage.this, R.raw.background);
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
player.setLooping(true); // Set looping
player.setVolume(volume, volume);
player.start();
return null;
}
}
For Playing:
mBackgroundSound = new BackgroundSound();
mBackgroundSound.execute();
For Stop:
mBackgroundSound.cancel(true);
if (player != null) {
player.stop();
player.release();
}
For Pause:
if (player != null) {
player.pause();
}
Try this it will help you....
//Click Listener on Image Button with play and Pause method
PLAY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Play-Pause();
}
});
//Play Pause method...........
public void Play-Pause(){
if (mediaPlayer.isPlaying()) {
PLAY.setImageResource(R.drawable.pause);
mediaPlayer.pause();
} else {
PLAY.setImageResource(R.drawable.play);
mediaPlayer.start();
}
}
Once a media player is stopped, you need to call prepare on it again to get it to a state where you can call start(). Look at the state diagram here http://developer.android.com/reference/android/media/MediaPlayer.html#pause%28%29
Check this code, its better and simple solution !
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
Switch sw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this,R.raw.nokia);
sw = findViewById(R.id.sw);
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mp.setLooping(true);
}
});
}
public void play(View v){
mp.start();
}
public void pause(View v){
if(mp.isPlaying())
mp.pause();
}
public void stop(View v){
if(mp.isPlaying()) {
boolean loop=mp.isLooping();
mp.stop();
mp = MediaPlayer.create(this, R.raw.nokia);
mp.setLooping(loop);
}
}
}