Connecting Seekbar with Hardware buttons on device - android

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.

Related

SeekBar wont display current position, but still plays the music on the position the user wanted

I recently posted a question that asks how SeekBars are operated. And someone directed me to this website/tutorial: http://android-mantra.blogspot.com/2013/09/seekbar-for-music-player.html
It really helped me alot and helped me understand how seekbars work, but I still have a problem. When I click the play button, the music will play, but when i seek the music, the seekbar will stay at position 0, although the music is runing on the position I wanted. Here is my code that i based (copy) from the tutorial.
package com.example.danbrianarenas.musictesterv2;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;
public class MainActivity extends Activity implements Runnable,View.OnClickListener,SeekBar.OnSeekBarChangeListener
{
SeekBar seekBar;
Button startMedia;
Button stopMedia;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
public void run()
{
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp !=null && currentPosition<total)
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
} catch (Exception e){
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View view){
if(view.equals(startMedia)){
if(mp == null){
mp=MediaPlayer.create(getApplicationContext(), R.raw.filc2);
seekBar.setEnabled(true);
}
if(mp.isPlaying()){
mp.pause();
startMedia.setText("Play");
}
else{
mp.start();
startMedia.setText("Pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
if (view.equals(stopMedia) && mp!=null){
if (mp.isPlaying() || mp.getDuration()>0){
mp.stop();
mp = null;
startMedia.setText("play");
seekBar.setProgress(0);
}
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
try{
if(mp.isPlaying() || mp!=null){
if(fromUser)
mp.seekTo(progress);
}else if (mp==null){
Toast.makeText(getApplicationContext(),"Media is not running!",Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
}catch (Exception e){
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar){
//TODO Auto-generated method sub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar){
//TODO Auto-generated method sub
}
}
PS: please tell me if you need the XML file. :) TIA
As you are not chaning the position of seekbar on your seekbar change listener update your code and it will work:
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
try{
if(mp.isPlaying() || mp!=null){
if(fromUser){
seekBar.setProgress(progress); // ************** you have to add this line
mp.seekTo(progress);
}}else if (mp==null){
Toast.makeText(getApplicationContext(),"Media is not running!",Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
}catch (Exception e){
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}

android mediaplayer double play

I have a problem. This is stream player it is playing fine but when I start play, change app and again start player app the stop button is disabled.
If I pressing play again - it start plaing double music and I cannot stop first stream playing.
In short: I need one app and one sound and possibility to stop sound (without double playing)
import com.erkutaras.media.audio.url.R;
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://play.org.ua:8000/";
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);
}
}
In your OnClick() method add if:
if (mediaPlayer.isPlaying())
{
//mediaPlayer.pause; //or what you want instead double play
}
else
{
//your code
}

android force close on clicking on seekbar

i'm newbie to android programming. i have the following code but i have a problem. when i click on the seekbar without playing the sound it force close. i mean when i click the play button i can click and seek on the seekbar but without clicking the play button clicking on the seekbar will cause force close. what's the problem?!
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity implements Runnable, OnClickListener, OnSeekBarChangeListener{
private SeekBar seekBar;
private ImageButton startMedia;
private ImageButton pauseMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioControl();
}
public void AudioControl(){
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (ImageButton) findViewById(R.id.playbutton);
pauseMedia = (ImageButton) findViewById(R.id.pausebutton);
seekBar.setOnSeekBarChangeListener(this);
startMedia.setOnClickListener(this);
pauseMedia.setOnClickListener(this);
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp != null && mp.isPlaying()) return;
if(seekBar.getProgress() > 0) {
mp.start();
return;
}
mp = MediaPlayer.create(MainActivity.this, R.raw.lone);
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
if (v.equals(pauseMedia) && mp!=null) {
mp.pause();
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
}
and i have another question:
i wanna when the user clicks on play button the pause button become visible and when the user clicks on pause button it tuen invisble. what code should i wirte and please tell me where should i put this code.
Every method that manages the UI has to be called on the UI Thread itself:
You can not run
seekBar.setProgress(currentPosition);
on a Thread different frome the UIThread.

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.

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