How to create Button to control background sound. - android

I'm trying to add background music to my application. All I want is the sound should played on pressing the btnoptn Button and its text transitions into the "music off". The music should continue on any Activity until the settings page is returned to and the same Button is pressed again. The music then stops and the Button text changes to "music on".
This my code so far:
package hello.english;
import hello.english.R;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.media.MediaPlayer;
import android.os.Bundle;
public class welcome extends Activity implements OnClickListener{
private Button btnoptn;
private Button btnmenu;
public static MediaPlayer mp2;
private void btnoptn(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button testButton = (Button) findViewById(R.id.btnoptn);
testButton.setTag(1);
testButton.setText("Musik Of");
mp2=MediaPlayer.create(this, R.raw.guitar_music);
mp2.start();
mp2.setLooping(true);
testButton.setOnClickListener( new View.OnClickListener() {
public void onClick (View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
mp2.start();
mp2.setLooping(true);
testButton.setText("Musik Of");
v.setTag(0); //pause
} else {
mp2.pause();
testButton.setText("Musik On");
v.setTag(1);
} //pause
}
});
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
btnoptn=(Button)findViewById(R.id.btnoptn);
btnmenu=(Button)findViewById(R.id.btnmenu);
btnoptn.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
btnoptn(null);
}
});
btnmenu.setOnClickListener( new View.OnClickListener() {
public void onClick(View view2) {
btnmenu();
}
});
}
protected void btnmenu() {
try {
Intent btnmenu= new Intent (this, menuenglish.class);
startActivity(btnmenu);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onStart() {
super.onStart();
btnoptn.setTag(0);
}
public void onClick(View view2) {
// TODO Auto-generated method stub
}
}

This is a really simple example. I don't know how it works if you switch between Activities, i never really worked with the MediaPlayer class.
public class MainActivity extends Activity
{
private MediaPlayer mediaPlayer;
private Button musicButton;
private OnClickListener listener = new OnClickListener()
{
// a boolean value in the names Onclicklistener class.
// this will help us to know, if the music is playing or not.
boolean isPlaying = false;
#Override
public void onClick(View arg0)
{
if(isPlaying)
{
mediaPlayer.pause(); //stop the music
musicButton.setText("Start"); //change the buttons text
}
else
{
mediaPlayer.start(); //start the music
musicButton.setText("Stop"); //change the text
}
//changing the boolean value
isPlaying = !isPlaying;
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Creating the mediaplayer with a desired soundtrack.
mediaPlayer = MediaPlayer.create(this, R.raw.my_music);
//Getting the Button reference from the xml
musicButton = (Button) findViewById(R.id.music_button);
//Setting the listener
musicButton.setOnClickListener(listener);
}
}

Related

Android: I click on the button to play the sound

I'm creating piano app but I got problem when i click on the button to play many times i can't hear sound when i click on the button again. After i click on the button many times all the sounds are not heard how to solve this problem?
public class Music_piano extends Activity {
Button btn_s_ddo,btn_s_re,btn_s_mi,btn_s_fa,btn_s_so,btn_s_la,btn_s_si,btn_ldo;
MediaPlayer mp = new MediaPlayer();
MediaPlayer mp1,mp2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_music_piano);
}
public void btn_sound_ddo(View v){
mp = MediaPlayer.create(this, R.raw.ddo);
mp.start();
}
public void btn_sound_re(View v){
mp = MediaPlayer.create(this, R.raw.re);
mp.start();
}
public void btn_sound_mi(View v){
mp = MediaPlayer.create(this, R.raw.mi);
mp.start();
}
public void btn_sound_fa(View v){
mp = MediaPlayer.create(this, R.raw.fa);
mp.start();
}
public void btn_sound_so(View v){
mp = MediaPlayer.create(this, R.raw.sol);
mp.start();
}
public void btn_sound_la(View v){
mp = MediaPlayer.create(this, R.raw.la);
mp.start();
}
public void btn_sound_si(View v){
mp = MediaPlayer.create(this, R.raw.si);
mp.start();
}
public void btn_sound_ldo(View v){
mp = MediaPlayer.create(this, R.raw.ddo_last);
mp.start();
}
}
Can you please try below code ? I have tried it, worked well for me.
Button btnOne = (Button)findViewById(R.id.btnOne);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mPlayer = MediaPlayer.create(TempActivity.this, R.raw.mysoundfile);
mPlayer.start();
}
});
Hope it will help you.
its better to create single instance of MediaPlayer and reuse it
MediaPlayer mMediaPlayer = new MediaPlayer(); // global variable
//write below code on buttons onclick method
AssetFileDescriptor assetFile = context.getAssets().openFd(audioFile);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(assetFile.getFileDescriptor(),
assetFile.getStartOffset(), assetFile.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
I wrote a simple SoundManager class with a demo activity. No comment whatsoever as I think its pretty easy to read. Refer to SoundPool for details.
SoundManager class
package com.makeez.sfx;
import android.content.Context;
import android.media.SoundPool;
import java.util.HashMap;
import java.util.Map;
public class SoundManager {
private final Map<Integer, Integer> sfxId = new HashMap<>();
private SoundPool sfx;
public SoundManager(int maxStreams, int streamType, int srcQuality) {
sfx = new SoundPool(maxStreams, streamType, srcQuality);
}
public void load(Context context, int... resources) {
if (context == null) {
throw new NullPointerException("Context must not be null.");
}
if (resources == null) {
return;
}
for (int resource : resources) {
int soundId = sfx.load(context, resource, 1);
sfxId.put(resource, soundId);
}
}
public void play(int resId) {
Integer soundId = sfxId.get(resId);
if (soundId != null) {
sfx.play(soundId, 1.0f, 1.0f, 0, 0, 1.0f);
}
}
public void release() {
if (sfx != null) {
sfx.autoPause();
sfx.release();
sfx = null;
}
}
}
Demo activity
package com.makeez.sfx;
import android.media.AudioManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private SoundManager manager;
private int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = new SoundManager(1, AudioManager.STREAM_MUSIC, 0);
manager.load(this, R.raw.sfx_0001, R.raw.sfx_0002, R.raw.sfx_0003, R.raw.sfx_0004, R.raw.sfx_0005);
Button button = (Button) findViewById(R.id.play);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position) {
case 0: manager.play(R.raw.sfx_0001); break;
case 1: manager.play(R.raw.sfx_0002); break;
case 2: manager.play(R.raw.sfx_0003); break;
case 3: manager.play(R.raw.sfx_0004); break;
case 4: manager.play(R.raw.sfx_0005); break;
}
if (++position >= 5) {
position = 0;
}
}
});
}
#Override
protected void onDestroy() {
manager.release();
super.onDestroy();
}
}

change button image onClick android

I have a button and two images, i want the default image for the button to be btn1.jpg and when the button is clicked, the image should immediately change to btn2.jpg and after 3 seconds, it should again revert back to btn1.jpg. please tell me how do i achieve this?
package com.example.btn;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private View ButtonName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void yolo(View v) {
switch (v.getId()) {
case R.id.buttonName:
ButtonName.setBackgroundResource(R.drawable.btn2);
//Disable click on Button
ButtonName.setEnabled(false);
try {
Thread.sleep(3000);
}
catch (Exception e) {
e.printStackTrace();
}
ButtonName.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
case default:
ButtonName.setBackgroundResource(R.drawable.btn1);
}
}
}
You must change the button background image in the OnClick method to btn2.jpg. After that, you must start a timer to count down 3 seconds and, after that, change again the button image to btn1.jpg
private final int interval = 3000;
private Handler handler = new Handler();
private Runnable runnable
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
btn.setBackground(getResources().getDrawable(R.drawable.btn2))
//Start runnable after 3 seconds
handler.postDelayed(runnable, interval);
}
});
runnable = new Runnable(){
public void run() {
btn.setBackground(getResources().getDrawable(R.drawable.btn1))
}
};
finally figured it out myself!
Set background for button in xml
use this code:
package com.example.btn;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
public class MainActivity extends Activity {
Handler mHandler; // global instance
Runnable your_runnable; // global instance
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void yolo(final View view) {
if (view == view) {
view.setBackgroundResource(R.drawable.btn1);
mHandler = new Handler();
your_runnable = new Runnable() {
#Override
public void run() {
view.setBackgroundResource(R.drawable.btn2);
}
};
mHandler.postDelayed(your_runnable, 3000L);// 3sec timer
}
}
}
This may work for you!!
public class MainActivity extends Activity {
Button button;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.yourbuttonid);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
button.setBackgroundResource(getresources().getDrawable(R.drawable.btn1));
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
button.setBackgroundResource(getresources().getDrawable(R.drawable.btn2));
}
}, 3000);
}
});
}
Ok so first, you have a mistake here :
ButtonName.setBackgroundResource(getresources().getDrawable(R.drawable.btn2));
And after, add a clickListener on your button :
private Thread t = new Thread(new Runnable {
#Override
public void run() {
ButtonName.setBackgroundResource(getresources().getDrawable(R.drawable.btn2));
//Disable click on Button
ButtonName.setEnabled(false);
try {
Thread.sleep(3000);
}
catch (Exception e) {
e.printstacktrace();
}
ButtonName.setBackgroundResource(getresources().getDrawable(R.drawable.btn1));
}
});
ButtonName.setOnClickListener (new OnClickListener (
#Override
public void onClick(View v) {
t.start();
}
));
I think it is what you want

Text to Speech not playing sound for first time, but playing for the next time

I am using this kind of text to speech in one of my class in my app(Code edited to show outlook & exact requirement.). I will show some content on my view & if we click the button , I want to play the sound that is by using this texttospeech engine... But for First time it is not playing the sound. From the next click onwards the TEXTTOSPEECH engine is working nicely
Iwant to know how to overcome this issue....
public class LearnActivity extends Activity implements OnClickListener, OnInitListener {
AudioManager audioManager;
float volume;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learn);
textToSpeech = new TextToSpeech(this, this);
textToSpeech.setLanguage(Locale.US);
textToSpeech.setSpeechRate(0.95f);
method();
}
public void method(){
bt.setonClickListener(new onClickListener(){
public void onClick(View v){
playSound(datasource.getItemSound);
}
});
}
public void playSound(String sound){
textToSpeech.speak(sound,TextToSpeech.QUEUE_FLUSH,null);
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
NOTE:- This also meet my Requirement, How to play sound from TEXTTOSPEECH engine directly without using any onClicks etc.,... because I also wants to play a startup sound that too with Android's Text-To-Speech engine only...
That's because you are clicking the button before the engine is ready.
You have to check if the TTS engine has successfully initialized on your onInit() method and enable/disable the play button accordingly.
Assuming that bt in your code is some sort of View that has setEnabled(boolean) method:
#Override
public void onInit(int status) {
bt.setEnabled(status == TextToSpeech.SUCCESS);
}
You always have to assume that the engine has not been initialized and hence keep your play button disabled by default.
I used RXJava to make a class that solves this problem. If your TTS engine is not ready when you want to use the speak method it will wait for the engine to get ready and then speaks the given string.
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Pair;
import android.widget.Toast;
import java.util.Locale;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
public class Pronunciation {
private TextToSpeech textToSpeech;
private int languageResult;
private boolean noError;
private final String errorMessage="Something went wrong with your text to speech engine";
private PublishSubject<Boolean> engineIsReady=PublishSubject.create();
private PublishSubject<Pair<String,Integer>> speakObservable=PublishSubject.create();
private CompositeDisposable compositeDisposable=new CompositeDisposable();
public Pronunciation(Context context) {
textToSpeech=new TextToSpeech(context, status -> {
if (status!=TextToSpeech.ERROR){
languageResult= textToSpeech.setLanguage(Locale.ENGLISH);
engineIsReady.onNext(true);
} else {
Toast.makeText(context,errorMessage
,Toast.LENGTH_LONG).show();
}
});
if (languageResult==TextToSpeech.LANG_MISSING_DATA||languageResult== TextToSpeech.LANG_NOT_SUPPORTED){
noError =false;
Toast.makeText(context,errorMessage
,Toast.LENGTH_LONG).show();
}else { noError =true;}
compositeDisposable.add( Observable.combineLatest(speakObservable, engineIsReady,
(stringIntegerPair, aBoolean) -> stringIntegerPair)
.subscribeOn(Schedulers.io())
.subscribe(pair->{
if (noError)
textToSpeech.speak( (pair).first
,(pair).second,null,null);
}));
}
public void speak(String text,int queueMode){
speakObservable.onNext(new Pair<>(text,queueMode));
}
public void stop(){
if (textToSpeech!=null){
textToSpeech.stop();
textToSpeech.shutdown();
}
compositeDisposable.clear();
}
}
first add RxJava dependency in your Gradle file
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
Then create an instance of this class in the onCreate method of your activity or fragment.Now you can pass the string and queue mode to the speak method.
pronunciation.speak("Hi", TextToSpeech.QUEUE_FLUSH));
Don't forget to call the stop method in onDestroy or onDetach to avoid memory leak
#Override
public void onDetach() {
super.onDetach();
pronunciation.stop();
}
you should write your program ...
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnUtteranceCompletedListener {
TextToSpeech t1;
protected void onCreate(Bundle savedInstanceState) {
t1=new TextToSpeech(MainActivity.this, MainActivity.this);
}/////on creat
protected void onDestroy() {
if(t1!=null) {
t1.stop();
t1.shutdown();
t1=null;
}
super.onDestroy();
}
public void onInit(int arg0) {
t1.setOnUtteranceCompletedListener(this);
}
}//mainactivity
Add this command when button is clicked or everywhere you want to speak text.
t1.speak(text, TextToSpeech.QUEUE_FLUSH, null);
Just Put Delay For 5 Second And It's Working without any button Click
public class Final_Text_To_Speech_Activity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private TextToSpeech tts; // For Text to Speech
CardView ScanProduct, SearchProduct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
init();
// Just Put Delay For 5 Second And It's Working without any button Click
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
SpeakOutOnce("Welcome to Text To Speech Application");
}
}, 5000);
}
#Override
protected void onResume() {
super.onResume();
}
public void init() {
ScanProduct = (CardView) findViewById(R.id.scan_product);
SearchProduct = (CardView) findViewById(R.id.search_product);
// Search On Button Click
ScanProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut("You have Just pressed Scan Option");
}
});
SearchProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut("You have Just pressed Search Option ");
}
});
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
int result = tts.setLanguage(Locale.US);
if (status == TextToSpeech.SUCCESS) {
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
} else {
speakOut("");
}
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
private void speakOut(String text) {
tts.setPitch(1.0f); //Normal Pitch
tts.setSpeechRate(0.7f); // 1.0 is Normal speech Rate
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
private void SpeakOutOnce(String text) {
if (tts != null) {
tts.setPitch(1.0f); //Normal Pitch
tts.setSpeechRate(0.7f); // 1.0 is Normal speech Rate
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}

how to add soundeffects when clicking a button

I'm having a bit of a trouble,, here's the gen. idea,, I have created an app a simple game-like application.. however the problem is when I try to click the button in the title screen it doesn't play the click sound.. can anyone please help me.. here's the code for my sound
public class Effects extends Activity implements MediaPlayer.OnCompletionListener {
Button mPlay;
MediaPlayer mPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlay = (Button)findViewById(R.id.btnStart);
mPlay.setOnClickListener(playListener);
setContentView(R.layout.activity_main);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mPlayer != null) {
mPlayer.release();
}
}
private View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer == null) {
try {
mPlayer = MediaPlayer.create(Effects.this, R.raw.button11);
mPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
} else {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
};
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
}
and here's my code for the main java that I want the sound to be played when I clicked this button
public class Main extends Activity implements OnClickListener
{
Button about;
Button Quit;
Button start;
protected void onCreate(Bundle onSavedInstanceState) {
super.onCreate(onSavedInstanceState);
setContentView(R.layout.activity_main);
about = (Button)findViewById(R.id.btnAbout);
about.setOnClickListener(this);
Quit = (Button)findViewById(R.id.btnQuit);
Quit.setOnClickListener(this);
start = (Button)findViewById(R.id.btnStart);
start.setOnClickListener(this);
}
public void onClick(View argo)
{
if(argo.getId()==R.id.btnAbout)
{
Intent i = new Intent(this,About.class);
this.startActivity(i);
}
if(argo.getId()==R.id.btnQuit)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
if(argo.getId()==R.id.btnStart)
{
Intent start = new Intent(this,Howto.class);
this.startActivity(start);
Intent svc=new Intent(this,Effects.class);
startService(svc);
}
}
}
Use SoundPool to play your sounds: http://developer.android.com/reference/android/media/SoundPool.html you should init sounds in your onCreate() and then play them back in onClick()
And instead of doing thousands of pointless if(argo.getId()==R.id.btnQuit) (you should at least use else) get familiar with switch/case syntax)

Android Media Player play/pause Button

In my project, I am playing music file in android media player by using the following code
MediaPlayer mPlayer = MediaPlayer.create(MyActivity.this, R.raw.myfile);
mPlayer.start();
the above is coded in the onclick of the play button.
I want to pause the playback by clicking the same button again.ie) single button for play/pause.
How shall i do this.
You could use simple if-check to handle the pausing. Try this:
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}
Please try this::
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;
}
}
});
Inside the button click check for mediaPlayer.isPlaying(). This will return true if the media player is playing else false.
So now with this, flag value you can make a if statement and switch to play or pause like this,
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
} else {
mediaplayer.start();
}
}
});
Below code takes care of your play/pause button click event along with forward and backward buttons for forward and backward seek on the seekbar provided (which is synchronized with the media track). Currently it plays just ONE song. However, you can add to that. This is my first media player using mediaplayer class, so you might find it a bit primitive. However if you need you can also check out the VideoView examples. It's apparently easier with VideoView as the standard media console is already present in the form of pre-defined widgets. so that makes designing the player much easier.
package in.org.Test;
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.ProgressBar;
import android.widget.SeekBar;
import android.widget.Toast;
public class Test12Activity extends Activity implements OnClickListener,Runnable {
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
private SeekBar seek;
MediaPlayer player = new MediaPlayer();
private ImageButton plus,minus;
ImageButton im;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
plus = (ImageButton) findViewById(R.id.imageButton2);
minus = (ImageButton) findViewById(R.id.imageButton3);
player = MediaPlayer.create(this, R.raw.sound2);
player.setLooping(false);
im = (ImageButton) this.findViewById(R.id.imageButton1);
seek = (SeekBar) findViewById(R.id.seekBar1);
seek.setVisibility(ProgressBar.VISIBLE);
seek.setProgress(0);
seek.setMax(player.getDuration());
new Thread(this).start();
im.setOnClickListener(this);
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { int cu = player.getCurrentPosition(); player.seekTo(cu-5000); }});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {int cu = player.getCurrentPosition(); player.seekTo(cu+5000);}});
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.imageButton1) {
if(player.isPlaying()) {
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.play);
}
else
{
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.pause);
}
}
}
#Override
public void run() {
int currentPosition= 0; String s;
int total = player.getDuration();
while (player!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= player.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek.setProgress(currentPosition);
}
}
}
MediaPlayer mpE = MediaPlayer.create(GuitarTuner.this, R.raw.test2 );
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mpE.isPlaying()) {
mpE.pause();
play.setBackgroundResource(R.drawable.play);
} else {
mpE.start();
play.setBackgroundResource(R.drawable.pause);
}
}
});
For pausing the Mediaplayer:
Mediaplayer.pause();
length = Mediaplayer.getCurrentPosition();
and for resuming the player from the position where it stopped lately is done by:
Mediaplayer.seekTo(length);
Mediaplayer.start();
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//the song was previously saved in the raw folder. The name of the song is mylife (it's an mp3 file)
final MediaPlayer mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.mylife);
// Play song
Button playButton = (Button) findViewById(R.id.play);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.start(); // no need to call prepare(); create() does that for you
}
});
// Pause song
Button pauseButton = (Button) findViewById(R.id.pause);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.pause();
}
});
// Stop song - when you stop a song, you can't play it again. First you need to prepare it.
Button stopButton = (Button) findViewById(R.id.stop);
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.stop();
mMediaPlayer.prepareAsync();
}
});
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = button.getText().toString();
if (text.equals("play")){
mediaPlayer.start();
button.setText("pause"); //changing text
}
else if (text.equals("pause")){
mediaPlayer.pause();
button.setText("play"); //changing text
}
}
});
very simple solution. If mediaplayer is playing, display play button and pause the mediaplayer. If not playing, do the opposite.
playBtn.setOnClickListener(view -> {
//events on play buttons
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.play);
} else {
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.pause);
}
});

Categories

Resources