Toggle VideoView's audio with a Button - java

I am using a videoView to play a video.
bVideoView = (VideoView) findViewById(R.id.bVideoView);
bVideoView.setVideoPath(videoPath);
Now I have a button,
audioToggle = (Button) findViewById(R.id.audioToggle);
Then I have the Button's OnClickListener
private static int aux = 0;
private AudioManager mAudioManager;
audioToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bVideoView.start();
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if(aux % 2 == 0){
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 50, 0);
aux++;
} else {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
aux++;
}
}
});
Now with this OnClickListener I am perfectly able to toggle the audio to mute and unmute when it is clicked each time. However I want something like this,
On the first click the videoView should start.
When I keep pressing the button the audio must mute.
When I release the button the audio must unmute.
I have been trying a lot and failing in some or the other way. Please help.

Do you mean:
The first time I hold the button, the video should play.
While I'm holding the button the audio must be heard.
When I release the button, the audio must be muted.
When I press and hold the button again, the audio must be heard again.
Then what you therefore need is not an OnClickListener but rather an OnTouchListener
What happens under the hood is that your OnClickListener is always called after you release your finger. Using View.OnTouchListener you can dispatch events when you press (you mean touch and hold) and release.
See http://developer.android.com/reference/android/view/View.OnTouchListener.html
Here's a sample snippet:
private static int aux = 0;
private AudioManager mAudioManager;
audioToggle.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent e) {
bVideoView.start();
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch(e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 50, 0);
break;
case MotionEvent.ACTION_UP:
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
break;
}
return true;
}
}
Finally, I don't recommend controlling the system's volume. Use a MediaPlayer.OnPreparedListener instead, get the VideoView’s MediaPlayer and then play around with its volume.
Edit:
Here's another sample snippet:
private MediaPlayer bVideoViewMP;
bVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// Fetch a reference
bVideoViewMP = mp;
}
});
audioToggle.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent e) {
bVideoView.start();
switch(e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
bVideoViewMP.setVolume(0.75f, 0.75f);
break;
case MotionEvent.ACTION_UP:
bVideoViewMP.setVolume(0, 0);
break;
}
return true;
}
}
These should be placed either on your fragment's onViewCreated() or on your activity's onCreate() method before the VideoView has been fully prepared.

Related

How To Use OnTouchListener To Open New Activity

I Tried OnClickListener an OnLongClickListener And yea it worked but those are too quick and i want to make them even more longer and i am just unable to use OntouchListener To Open New Activity And i have no clue almost tried everything nothing worked
Activity Name: Website
Button id: action_button (its a floatingActionbutton)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton actionButton = findViewById(R.id.action_button);
defineView();
handleIntent();
defineActionBar();
checkPermission();
//i tried both here
public void openWebsite() {
Intent intent = new Intent(this, Website.class);
startActivity(intent);
Not sure why you want to use OnTouchListener instead of OnClickListener since I don't think there is any difference between them referring to button events.
whit OnClickListener you could capture long press with:
button.setOnLongClickListener {
//ACTION
true
}
EDIT: (for custom duration, you should use OnTouchListener, thats right)
you can do something like this:
long time = 0;
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
time = System.currentTimeMillis();
}
else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
double duration = (System.currentTimeMillis() - time / 1000.0);
if(duration > 5){
action2();
return true;
}else if(duration > 3.2){
action1();
return true;
}
}
return false;
}
});

Not Allowing Multiple Button Presses

I'm building a camera app with Camera2 API, relatively new to Android development. Everything is working just working out the bugs. But I have a switch camera button, going from the front camera to the back or vise-versa. If the user continuosly presses the button, the app will crash. Trying to set it up in a way that it finishes everything it needs to do before the button can be used again.
I have the button set to enabled, but after press, it disables the button until everyting finishes, then renables, but that doesn't seem to work:
//The button to switch the camera to front and back camera.
mChangeCamera = (ImageButton) findViewById(R.id.change_camera);
mChangeCamera.setEnabled(true);
mChangeCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mChangeCamera.setEnabled(false);
closeCamera();
// stopBackgroundthread();
if (mTextureView.isAvailable()) {
setUpCamera(mTextureView.getWidth(), mTextureView.getHeight());
transformImage(mTextureView.getWidth(), mTextureView.getHeight());
connectCamera();
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
mChangeCamera.setEnabled(true);
}
});
there has to be a simple way to do this, but not finding anyting from searchs. Anyone know how I can set it up not to crash when the user smashes the button?
Alight, so I ended up figuring out how to do this. You can use a handler with a post delay like so:
mChangeCamera = (ImageButton) findViewById(R.id.change_camera);
mChangeCamera.setEnabled(true);
mChangeCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mChangeCamera.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mChangeCamera.setEnabled(true);
}
},1000);
closeCamera();
// stopBackgroundthread();
if (mTextureView.isAvailable()) {
setUpCamera(mTextureView.getWidth(), mTextureView.getHeight());
transformImage(mTextureView.getWidth(), mTextureView.getHeight());
connectCamera();
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}
}
});
i did this by calculate time between multiple button presses...
create global variable in your class first
private long mLastClickTime = 0;
and a final int for duration between clicks
public static final int CLICK_TIME = 400;
then paste this code in on click of button
if (SystemClock.elapsedRealtime() - mLastClickTime < CLICK_TIME) {
return; //button pressed repeatedly so do nothing
}
mLastClickTime = SystemClock.elapsedRealtime();
// button is not pressed repeatedly so add your desired action
and of course you can increase the CLICK_TIME value if error still occurs

How to play sound in custom keyboard

I've recently made my own keyboard that is always shown to the user.
I've also found how to play sounds while pressing a key but if I press one and then inmediatly another, only plays the first sound.
Is there any way for making the sound to be played each time I press a key even if there's 0,1 millisecond between them?
Here is my code:
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sn_tecla);
final MediaPlayer mpspc = MediaPlayer.create(this, R.raw.sn_spc);
texto1.setTypeface(fuente);
//This is for each key.
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
texto1.setText(texto1.getText() + "1");
}
});
Thank you in advance.
use soundpool
http://developer.android.com/reference/android/media/SoundPool.html
SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
/** soundId for Later handling of sound pool **/
int soundId = sp.load(MainActivity.this, R.raw.windows_8_notify, 1); // in 2nd param u have to pass your desire ringtone
sp.play(soundId, 1, 1, 0, 0, 1);
You can solve your problem by declaring a mediaPlayer object for each of your buttons(a slight overhead, but it works).
Also, instead of an onClickListener, use an onTouchListener.
For example: If you have 2 buttons and each have to make the same sound, Your code will go like this:
final MediaPlayer[] mediaPlayers = new MediaPlayer[2];
for(int i =0;i<2;i++){
//if both buttons ought to have the same sound
mediaPlayers[i] = MediaPlayer.create(getApplicationContext(), R.raw.beep);
mediaPlayers[i].setLooping(true);
}
button1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//when the user presses the button
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
mediaPlayers[0].start();
texto1.setText(texto1.getText() + "1");
}
//when the user releases the button
if(event.getAction() == MotionEvent.ACTION_UP){
mediaPlayers[0].pause();
}
return false;
}
});
button2.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
mediaPlayers[1].start();
texto1.setText(texto1.getText() + "1");
}
if (event.getAction() == MotionEvent.ACTION_UP) {
mediaPlayers[1].pause();
}
return false;
}
});
Hope this works for you!

Android stopping the previous mediaplayer?

I have 3 toggle buttons. I had it working that when clicked it would play a sound and the button would toggle to "stop". when the sound is finished it would toggle back to "play" If you click "stop" while it is playing the sound will stop and toggle back.
However my problem is that if I click two buttons and they both were playing I could not stop the previous one. This is because I could not access the previous mediaPlayer only the current. Here is my current attempt, any help would be great, thanks!
#Override
public void onClick(View v)
{
int soundFile = 0;
switch (v.getId())
{
case (R.id.btnSound1):
soundFile = R.raw.sound1;
break;
case (R.id.btnSound2):
soundFile = R.raw.sound2;
break;
case (R.id.btnSound3):
soundFile = R.raw.sound3;
break;
}
final ToggleButton button = (ToggleButton) findViewById(v.getId()); //gets current button
MediaPlayer media = (MediaPlayer) button.getTag(); //gets mediaPlayer object stored in button
if(button.getTag().equals(null)) //only runs this once, if the mediaPlayer stored object is null (doesn't exist)
{
media = getMedia(soundFile);
button.setTag(media); //set the new media object to the buttons tag
media.start();
media.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) //when sound is over
{
button.setChecked(true); //set back to play
mp.release();
}
});
button.setOnCheckedChangeListener(new OnCheckedChangeListener(){ //when clicked
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
{
if(button.isChecked()) // if stop toggle clicked
{
button.setChecked(true); // set to play
MediaPlayer media = (MediaPlayer) button.getTag();
media.release(); //stop the sound
}
else if(!button.isChecked()) //if play toggle clicked
{
MediaPlayer media = (MediaPlayer) button.getTag();
media.start(); //play the sound
button.setChecked(false); //set to stop
}
}
});
}
}
public MediaPlayer getMedia(int sound)
{
MediaPlayer mediaPlayer = MediaPlayer.create(getBaseContext(), sound);
mediaPlayer.setVolume(100,100); //sets the volume to max
return mediaPlayer;
}

Button Down Event in Eclipse (Android)

I wanna use a button (not a key) just like backspace so when it is down do something repeatedly.
I've found proper code for hardware keys but as I mentioned I want a BUTTON do such things.
Thanks
You can set an OnTouchListener on a Button instance. You can then override the onTouch method of the of the listener to do what it is that you want until MotionEvent passed to the onTouch method has MotionEvent.getAction == MotionEvent.ACTION_UP. See this link for an example:
Android onTouch Listener event
A switch statement is sufficient, just customize it to fit your needs using what I said above. --hope this helps, Scott
Thanks Scott. Finally I found the answer and did the job.
public MyActivity extends Activity
{
private Handler mHandler = new Handler();
private Runnable mUpdateTask = new Runnable()
{
public void run()
{
Log.i("repeatBtn", "repeat click");
mHandler.postAtTime(this, SystemClock.uptimeMillis() + 100);
}
};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button repeatButton = (Button) findViewById(R.id.repeatButton);
repeatButton.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View view, MotionEvent motionevent)
{
int action = motionevent.getAction();
if (action == MotionEvent.ACTION_DOWN)
{
Log.i("repeatBtn", "MotionEvent.ACTION_DOWN");
mHandler.removeCallbacks(mUpdateTask);
mHandler.postAtTime(mUpdateTask, SystemClock.uptimeMillis() + 100);
}
else if (action == MotionEvent.ACTION_UP)
{
Log.i("repeatBtn", "MotionEvent.ACTION_UP");
mHandler.removeCallbacks(mUpdateTask);
}
return false;
}
});
}
}

Categories