How to change device volume from seek bar in android - android

I know how to control volume of media player from seekbar.But how can i do to change system volume from seekbar in android.

Use AudioManager and methods like adjustStreamVolume(). Here is a sample application that uses SeekBar widgets to adjust the volumes of various streams.

The following code can be used :
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar)findViewById(R.id.seekBar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}

Related

seek bar and media player android

I am Making a very simple video player app with play/pause button and a seek bar.
But when I change position of seek bar the video starts playing from starting.
I have tried many solutions to do this but I cannot resolve this.
Please anybody may help me to resolve this.
I am learning the android development and I am a beginner So please give me some tips if you can.
package com.example.videoplayer;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private Button button;
private SeekBar seekBar;
private SurfaceView surfaceView;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Objects.requireNonNull(getSupportActionBar()).hide();
button = findViewById(R.id.button);
seekBar = findViewById(R.id.seekBar);
surfaceView = findViewById(R.id.surfaceView);
mediaPlayer = MediaPlayer.create(this,R.raw.kh);
surfaceView.setKeepScreenOn(true);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(#NonNull SurfaceHolder surfaceHolder) {
mediaPlayer.setDisplay(surfaceHolder);
}
#Override
public void surfaceChanged(#NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(#NonNull SurfaceHolder surfaceHolder) {
}
});
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
button.setText("play");
}
else {
mediaPlayer.start();
button.setText("pause");
}
}
});
}
}
Try using
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mediaPlayer.seekTo(progress * 1000);
}
}

Connecting Seekbar with Hardware buttons on device

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class pushke extends Activity {
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
MediaPlayer mp;
MediaPlayer mp2;
MediaPlayer mp3;
MediaPlayer mp4;
MediaPlayer mp5;
MediaPlayer mp6;
SeekBar seekGuns;
RelativeLayout rguns;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.guns);
initControls();
rguns=(RelativeLayout) findViewById(R.id.rguns);
mp=MediaPlayer.create(this, R.raw.hekler);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp2.isPlaying()){
mp2.pause();
mp2.seekTo(0);
}
if (mp3.isPlaying()){
mp3.pause();
mp3.seekTo(0);
}
if (mp4.isPlaying()){
mp4.pause();
mp4.seekTo(0);
}
if (mp5.isPlaying()){
mp5.pause();
mp5.seekTo(0);
}
if (mp6.isPlaying()){
mp6.pause();
mp6.seekTo(0);
}
if (mp.isPlaying()){
mp.pause();
mp.seekTo(0);
}
else{
mp.start();
}
}
});
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar)findViewById(R.id.seekGuns);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
int index = seekGuns.getProgress();
seekGuns.setProgress(index + 1);
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
int index = seekGuns.getProgress();
seekGuns.setProgress(index - 1);
return true;
}
return super.onKeyDown(keyCode, event);
}
I am trying to connect hardware buttons to my seekbar so when I click on volume buttons, seekbar which is used for volume, increase-decrease depending on which button I pressed.
I got this code which is supposed to be working, but I have no idea why it's not working in my case, everytime I launch my app on phone as emulator, and use hardware volume button app crashes.
I get this in LoGcat but Ican't figure out how to fix it or where is the problem because eclipse is not showing me any errors.
Here is my logcat: http://i.imgur.com/o4qSvCv.png
This is because you have declared two Seekbar variables.
private SeekBar volumeSeekbar = null;
SeekBar seekGuns;
and in your onKeyDown method you are using seekGuns named variable which is not initialized.
So you have two option.
1) Initialize means find the id for seekguns variable.
2) Use volumeSeekbar instead of seekguns in onKeyDown method.

seekbar not working when runnable and handler.postdelayed() are added in android apps

I'm not sure why I get error on the handler. The codes work until when I add in the handler to control the seekbar, it will prompt error.
package com.voice.recording.v3;
import android.app.Activity;
import android.media.MediaPlayer;
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;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class VoiceRecordingPlaybackv3Activity extends Activity implements OnCompletionListener,
OnTouchListener, OnClickListener, OnSeekBarChangeListener {
MediaPlayer mediaPlayer;
View theView;
Button stopButton, startButton, quitButton;
SeekBar seekBar;
Handler handler;
int position = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
stopButton = (Button)this.findViewById(R.id.StopButton);
startButton = (Button)this.findViewById(R.id.StartButton);
quitButton = (Button)this.findViewById(R.id.quitButton);
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
quitButton.setOnClickListener(this);
theView = this.findViewById(R.id.theview);
theView.setOnTouchListener(this);
mediaPlayer = MediaPlayer.create(this, R.raw.goodmorningandroid);
mediaPlayer.setOnCompletionListener(this);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setMax(mediaPlayer.getDuration());
}
public void onCompletion(MediaPlayer mp){
mediaPlayer.start();
mediaPlayer.seekTo(position);
}
public boolean onTouch(View v, MotionEvent me){
if(me.getAction() == MotionEvent.ACTION_MOVE){
if(mediaPlayer.isPlaying()){
position = (int)(me.getX()*
mediaPlayer.getDuration()/theView.getWidth());
Log.v("SEEK",""+position);
mediaPlayer.seekTo(position);
}
}
return true;
}
public void onClick(View v){
if(v == stopButton){
mediaPlayer.pause();
}else if(v == startButton){
try{
mediaPlayer.start();
startPlayProgressUpdater();
}catch(IllegalStateException e){
mediaPlayer.pause();
}
}else if(v == quitButton ){
mediaPlayer.stop();
mediaPlayer.release();
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
seekBar.setSecondaryProgress(seekBar.getProgress());
}
public void startPlayProgressUpdater() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification,100);
}else{
mediaPlayer.pause();
seekBar.setProgress(0);
}
}
}
The error I get is NullPointerException, can anyone please point out my mistaken
Your code shows handler is defined by not initialized. Please post stacktrace if that's not the problem.

Android making a ToggleButton to set the Ringtone to Vibrate

I am currently making an app with a SeekBar in which the SeekBar controls the Music Volume, Ringtone Volume, and Alarm Volume. It works fine but whenever I try to code in a button to set the phone to vibrate, it either crashes the app or it just breaks the code so the SeekBar never changes the volumes. Any help on how to achieve a button to set the phone to vibrate will be greatly appreciated. Thanks.
import android.app.*;
import android.os.*;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
private SeekBar Volume = null;
private AudioManager audioManager = null;
private TextView volumeValue;
private Vibrator sVibrate;
private ToggleButton vibrateButton;
final private String volumeIs = "Current Volume: ";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.main);
allVolumes();
}
private void allVolumes()
{
try
{
Volume = (SeekBar) findViewById(R.id.Volume);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Volume.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
Volume.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
sVibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrateButton = (ToggleButton) findViewById(R.id.vibrateButton);
volumeValue = (TextView) findViewById(R.id.volumeValue);
volumeValue.setText(volumeIs
+ Integer.toString(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC)));
Volume.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress,
boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
audioManager.setStreamVolume(AudioManager.STREAM_RING,
progress, 0);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM,
progress, 0);
volumeValue.setText(volumeIs
+ Integer.toString(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC)));
}
});
}
catch (Exception e)
{
e.printStackTrace();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(R.string.catch_error);
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Quit",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
finish();
}
});
builder.setNegativeButton("Ignore",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
Toast.makeText(
MainActivity.this,
"This app will not work right unless you restart.",
Toast.LENGTH_LONG).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
Any help on how to achieve a button to set the phone to vibrate will be greatly appreciated.
Do you mean, switch the phone to the vibration mode? Try this:
(AudioManager) getSystemService(AUDIO_SERVICE)).setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

MediaPlayer android doesnt play

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);
}
}

Categories

Resources