I have an application with a mute button. I have been stuck on this for 4 and a half hours now, so I am plain desperate. I am trying to have the volume mute when user clicks mute and unmute when user clicks it again. This works fine, except the audio isn't playing. For some reason, Stream_Music is 0?
public void mute(View view) {
mutebutton = (ImageButton) findViewById(R.id.mutebutton);
if ((variableForMute.x % 2) != 0) { //If it's odd UNMUTE
Log.v(TAG, "Use this volume to unmute " +userVolumeOnStart.userVolume +"");
Toast.makeText(Main_Menu.this, "UNMUTED", Toast.LENGTH_SHORT).show();
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, userVolumeOnStart.userVolume, 0);
variableForMute.x++;
} else { //If its even MUTE
userVolumeOnStart.userVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.v(TAG, "Right Before Mute " +userVolumeOnStart.userVolume +"");
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
Toast.makeText(Main_Menu.this, "MUTED", Toast.LENGTH_SHORT).show();
variableForMute.x++;
}
}
Here is the beginning where I declare the variables and objects:
ImageButton leftcenter;
ImageButton mutebutton;
final String TAG = "userVolume";
private AudioManager mAudioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__menu);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
leftcenter = (ImageButton) findViewById(R.id.startGame);
}
The thing is, as log outputs, I am getting the following:
I should have the volume change to what my volume was before I started my app. I want to be able to have the user unmute the app to the same volume that the user was originally on. But for some reason it is always 0!? Why is this happening? My phone volume is at full?!
Please help,
I have spent way too much time on this-I appreciate all feedback:
positive, negative, neutral, whatever.
I found the issue. I have changed STRAM_MUSIC to STREAM_RING, and the variable userVolumeOnStart.userVolume changes successfully!
btn_mute.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if(isChecked) {
btn_mute.setBackgroundResource(R.drawable.mute_bt);
audio.setStreamMute(AudioManager.STREAM_MUSIC, true);
} else {
btn_mute.setBackgroundResource(R.drawable.volume_bt);
audio.setStreamMute(AudioManager.STREAM_MUSIC, false);
}
}
});
Related
I have been stuck on this for over an hour now. In my main menu screen, I have a mute button. I want it to call a method in my background service, which mutes all of the MediaPlayer audio.
Here I am calling mute:
public void mute(View view){
mutebutton = (ImageButton) findViewById(R.id.mutebutton);
currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (currentVolume == 0) {
TwentySeconds.unMute();
Toast.makeText(Main_Menu.this, "UNMUTED", Toast.LENGTH_SHORT).show();
} else {
TwentySeconds.mute();
Toast.makeText(Main_Menu.this, "MUTED", Toast.LENGTH_SHORT).show();
}
Here are the methods in the service:
public static void mute(){
ten.setVolume(0, 0);
three.setVolume(0, 0);
}
public static void unMute(){
ten.setVolume(1, 1);
three.setVolume(1, 1);
}
Here are the actual media players, which play at intervals:
static `MediaPlayer` ten;
static `MediaPlayer` three;
The problem is, I am getting a null pointer exception here:
currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
By the way, manager is instantiated like so:
AudioManager manager;
and later on:
manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
I would really appreciate any feedback (positive or negative)! Thank you so much for all of your help, let me know if you need any more code.
{Rich}
Your "manager" should instantiated like this:
AudioManager manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
If this is still a nullpoint, add
Context context = this;
before your instantiation. Try it, wish I can help you.
How can I start the song from where I pressed pause button, help me out am new to media in android and am unaware from the media properties all the buttons are working fine , but I want to start the song where from at which point I stopped it -
public class MainActivity extends Activity {
MediaPlayer mediaPlayer;
Button play, stop,pause;
Uri path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
pause = (Button) findViewById(R.id.pause);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
path = Uri.parse("android.resource://" + getPackageName() + "/"+ R.raw.chelseafc);
mediaPlayer = MediaPlayer.create(MainActivity.this,path);
mediaPlayer.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
});
}
#Override
protected void onDestroy() {
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
super.onDestroy();
}
}
You have a start button, pause button and stop button. There is no Resume button. Also when you click start after pressing pause, media loads again and starts from beginning (length = 0). You have to seek it to the paused position and resume it :
Define a global variable :
int length = 0;
In pause listener:
length=mediaPlayer.getCurrentPosition();
In resume (create a resume listener):
mediaplayer.seekTo(length);
mediaPlayer.start();
UPDATE
Ideally pause and resume button would be same except you would toggle on-off with changing image resource between play and pause pngs and execute relevant code with help of a boolean variable :
In pause button listener:
if(play)
{
//paused
play =false;
pause.setImageResource(R.id.pause);
length=mediaPlayer.getCurrentPosition();
mediaPlayer.pause();
}else {
//resumed
play = true;
pause.setImageResource(R.id.resume);
mediaplayer.seekTo(length);
mediaPlayer.start();
}
Correct wherever necessary I typed in the editor not in IDE.
Use following code -
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
mediaPlayer.start();
mediaPlayer.pause();
mediaPlayer.reset();
I think it will help you.
How can I have an on and off state for an Image Button? My goal is to have sound play when the image button is clicked, and for sound to stop when the button is clicked again. Thank you!
you can use event's. like on click listener.
get your imageView and setOnClickListener for this.
ImageView mImageView = (ImageView) findViewById(R.id.sound_imageView);
Boolean flag = false;
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(flag) {
//play sound
flag = false;
} else {
//stop sound
flag = true;
}
}
});
There are a few Views that exist in Android that provide toggle functionality like you are looking for. You might want to research the android.widget.CompoundButton class for ideas, or reference this tutorial.
You can do it manually. First when you will click the button you will check whether the music is running or not. If it is running then stop it , if not running then play it.
Something like that -
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(musicPlayer!=null && musicPlayer.isPlaying()){
musicPlayer.stop();
}else{
musicPlayer=new MediaPlayer();
AssetFileDescriptor afd = getActivity().getAssets().openFd("AudioFile.mp3");
musicPlayer.setDataSource(afd.getFileDescriptor());
musicPlayer.prepare();
musicPlayer.start();
}
}
});
i have coded for media player and it is playing song .In the front end only image button is used and hardcoded as play button
when i click again it has to change image to pause state but the button which i have used is playing the song two times simultaneously whenever i click on it which is wrong
but i need the song to be paused so whereever i used
mp.start();
function which will be start to play the music from the url i added the code as
if(!mp.isPlaying()){
mp.start();
buttonPlayPause.setBackgroundResource(R.drawable.pause);
}else {
mp.pause();
buttonPlayPause.setBackgroundResource(R.drawable.play);}
but when i click the play button it starts playing and again if i click the button again it starts playing two times simultaneously
please help me how should i start and pause the mp3 file which i have displayed it in url it is not going to else block itself should i use different function
the full code of the project is
public class MainActivity5 extends Activity implements OnClickListener,
OnPreparedListener, OnErrorListener, OnCompletionListener {
MediaPlayer mp;
ProgressDialog pd;
Button bt;
ImageButton iv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main5);
iv = (ImageButton)findViewById(R.id.play);
iv.setOnClickListener(this);}
#Override
public void onPrepared(MediaPlayer mp)
{
Log.i("StreamAudioDemo", "prepare finished");
//pd.setMessage("Playing.....");
//mp.start();
/*if(mp.isPlaying()== true)
{
mp.start();
iv.setImageResource(R.drawable.pause);
}
else
{
mp.pause();
mp.release();
iv.setImageResource(R.drawable.play);
}*/
}
#Override
public void onClick(View v) {
try
{
pd = new ProgressDialog(this);
pd.setMessage("Buffering.....");
//pd.show();
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setDataSource("http://192.168.1.138/Android/music/vande.mp3");
mp.prepareAsync();
mp.setOnCompletionListener(this);
}
catch(Exception e)
{
Log.e("StreamAudioDemo", e.getMessage());
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
pd.dismiss();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
pd.dismiss();
Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
}}
thanks for your help in advance
i have commented some code above i have to re correct it
you can have a try at your onclickListener,when this player is playing,if you want to pause it ,you should to call MediaPlayer.pause() ,if you want to release it data,you can call MediaPlayer.release(),then ,you can play next music.
use this
public void onPrepared(MediaPlayer mp)
{
Log.i("StreamAudioDemo", "prepare finished");
//pd.setMessage("Playing.....");
// mp.start(); - this should be removed
if(mp.isPlaying()== true)
{
mp.pause();
iv.setImageResource(R.drawable.pause);
}
else
{
mp.start();
mp.release();
iv.setImageResource(R.drawable.play);
}
}
I have created an activity which includes media player in it.When I start activity, the music begins to play.But when the song is complete and when i click on back button on the emulator, it displays an error of (IllegellStateException).
Here is my code:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
imgVw.setImageResource(R.raw.teddy_two);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
Log.e("Current ","Position -> " + length);
mp.setLooping(false);
mp.start();
btnChapter.setEnabled(false);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mp.stop();
mp.release();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPause()
{
super.onStop();
SharedPreferences. Editor prefsEdit = prefs.edit();
int position = mp.getCurrentPosition();
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
mp.start();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
if(mp!= null)
{
mp.pause();
}
//finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Use finish(); in Activity class to stop Activity and return.
Try this
MediaPlayer player;
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "service started", 100).show();
if(player.isPlaying())
player.stop();
else
player.start();
return super.onStartCommand(intent, flags, startId);}
I think the problem is here:
#Override
public void onPause()
{
super.onPause();//should be onPause and not onStop
SharedPreferences. Editor prefsEdit = prefs.edit();
int position = mp.getCurrentPosition();
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
For more info read here.
Here's an implementation of onStop() that saves the contents of a draft note to persistent storage:
#Override
protected void onStop() {
super.onStop(); // Always call the superclass method first
// Save the note's current draft, because the activity is stopping
// and we want to be sure the current note progress isn't lost.
ContentValues values = new ContentValues();
values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());
getContentResolver().update(
mUri, // The URI for the note to update.
values, // The map of column names and new values to apply to them.
null, // No SELECT criteria are used.
null // No WHERE columns are used.
);
}
Although the onPause() method is called before onStop(), you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.
from android developer page: http://developer.android.com/training/basics/activity-lifecycle/stopping.html
if(mp!= null)
{
mp.pause();
}
The above code snippet inside if ((keyCode == KeyEvent.KEYCODE_BACK)) seems to be the problem. You should check whether the player is playing or not. If it is playing then only pause should be called.
You get (IllegelStateException) on the onPause().
To resolve this problem you need to put,
mp = null;
after,
mp.stop();
mp.release();
because when you check mp!=null that time MediaPlayer already release but not null.
so, if condition is correct and goto mp.pause() but mp already release that's why you get error.
Also you need to change name of MediaPlayer instance in onCompletion().
public void onCompletion(MediaPlayer mp)
because it is used mp of onCompletion() for stop() and release().
so, change mp to other(like: mp1).
check this is helpfull for you.