How To Mute Sound Video in VideoView Android - android

I want Mute Sound of video and use Videoview for playing video
_player.setVideoURI("/sdcard/Movie/byern.mp4");
_player.start();
Now,How can Resolve it?

You can custom VideoView like that
public class VideoPlayer extends VideoView implements OnPreparedListener, OnCompletionListener, OnErrorListener {
private MediaPlayer mediaPlayer;
public Player(Context context, AttributeSet attributes) {
super(context, attributes);
//init player
this.setOnPreparedListener(this);
this.setOnCompletionListener(this);
this.setOnErrorListener(this);
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) { }
#Override
public void onCompletion(MediaPlayer mediaPlayer) { ... }
public void mute() {
this.setVolume(0);
}
public void unmute() {
this.setVolume(100);
}
private void setVolume(int amount) {
final int max = 100;//change 100 to zeo
final double numerator = max - amount > 0 ? Math.log(max - amount) : 0;
final float volume = (float) (1 - (numerator / Math.log(max)));
this.mediaPlayer.setVolume(volume, volume);
}
}

You need to call MediaPlayer.OnPreparedListener and MediaPlayer.OnCompletionListener of you want to use VideoView .Then you can make setVolume method public so that volume can be controlled outside of the scope of the class.Below 3 will solve these..
Disabling sound in a video
Mute a playing video by VideoView in Android Application
Muting a video in a VideoView

Related

SoundPool not playing sound (while MediaPlayer does)

I am trying to play a sound in an app. However, using SoundPool I am unable to do so. The code is really simple and I don't see where it can fail.
A similar code but using MediaPlayer does work, but I am interested in using SoundPool.
SoundPool code:
private void playSound2(){
SoundPool sp = new SoundPool.Builder().build();
int soundID = sp.load(MainActivity.this, R.raw.sound, 1);
sp.play(soundID, 1, 1, 1, 0, 1);
}
Context:
public void goButtonClick(View view){
Button goButton = findViewById(id.button2);
if (onGoing){
goButton.setText("GO!");
} else {
goButton.setText("STOP");
//playSound(); // MediaPlayer
playSound2(); // SoundPool
}
onGoing = !onGoing;
}
MediaPlayer version (works):
private void playSound(){
MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.sound);
mediaPlayer.start();
}
Solved!
I was missing to wait for the loading of the sound file into soundPool. The correct code is:
private void playSound2() {
SoundPool sp = new SoundPool.Builder().build();
int soundID = sp.load(MainActivity.this, raw.sound, 1);
sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool sp, int soundID, int i1) {
sp.play(soundID, 1, 1, 1, 0, 1);
}
});
}

How to adjust the volume of two media players simultaneously?

I am running two media players simultaneously to play two different sounds, one is audio recording and second one is music. I am controlling the volume of both through two seekbars. The problem is, volume of one media player is controlled at once. When one media player is released, volume of other media player can be adjusted. I want to adjust SIMULTANEOUSLY
Here's my implementation.
public void setMediaPLayers() {
mediaPlayer = new MediaPlayer(); //TO PLAY VOICE RECORDING
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
try {
mediaPlayer.setDataSource(AudioSavePathInDevice); //VOICE RECORDING FILE PATH
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer2 = MediaPlayer.create(getActivity(), R.raw.sunnysideup); //FOR MUSIC FILE
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.start();
}
In seekbars, i am using audio manager to adjust volumes. In music seekbar, volume is adjusted through,
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0); // i = seekbar progress
Code for changing the volume of recording seekbar is,
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, i, 0); // i = seekbar progress
Here's the solution to play 2 media players simultaneously and control their volume through seekbars.
Create Variables
MediaPlayer mpOne = null;
MediaPlayer mpTwo = null;
SeekBar seekBarOne, seekBarTwo;
//Path to mp3 file stored in device
String FILE_PATH_ONE = Environment.getExternalStorageDirectory().getPath() + "/music_one.mp3";
String FILE_PATH_TWO = Environment.getExternalStorageDirectory().getPath() + "/music_two.mp3";
Function to intialize and start media players:
public void setMediaPlayers() {
mpOne = new MediaPlayer();
mpTwo = new MediaPlayer();
try {
mpOne.setDataSource(FILE_PATH_ONE);
mpTwo.setDataSource(FILE_PATH_TWO);
mpOne.prepare();
mpTwo.prepare();
mpOne.start();
mpTwo.start();
} catch (IOException e) {
e.printStackTrace();
}
}
Create SeekBarChangeListener to get the current progress.
SeekBar.OnSeekBarChangeListener seekBarOneListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
//Lets assume, seekbar's maximum progress is 10.
//i is the progress of seekbar between 0 to 10.
float volume = i * 0.10f;
//Set the volume if media player is not null
if (null != mpOne)
//volume is the float number between 0.0 and 1.0
mpOne.setVolume(volume, volume);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
SeekBar.OnSeekBarChangeListener seekBarTwoListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
//Lets assume, seekbar's maximum progress is 10.
//i is the progress of seekbar between 0 to 10.
float volume = i * 0.10f;
//Set the volume if media player is not null
if (null != mpTwo)
//volume is the float number between 0.0 and 1.0
mpTwo.setVolume(volume, volume);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
In activity or fragment
seekBarOne = (SeekBar) v.findViewById(R.id.seekBar1);
seekBarTwo = (SeekBar) v.findViewById(R.id.seekBar2);
seekBarOne.setOnSeekBarChangeListener(seekBarOneListener);
seekBarTwo.setOnSeekBarChangeListener(seekBarTwoListener);
//Start media players
setMediaPlayers();
//Completion listeners for releasing media players on completion.
mpOne.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mpOne.reset();
mpOne.release();
mpOne = null;
}
});
mpTwo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mpTwo.reset();
mpTwo.release();
mpTwo = null;
}
});

SoundManager, how to stop sound playing

I use simple SoundManager for play sounds from sounpool. My problem is, sound not stop playing when I exit from app, even I use mySound.release();.
Otherwise, everything works as it should, here is my code.
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class SoundManager {
private Context pContext;
private SoundPool mySound;
private float rate = 1.0f;
private float masterVolume = 1.0f;
private float leftVolume = 1.0f;
private float rightVolume = 1.0f;
private float balance = 0.5f;
// Constructor, setup the audio manager and store the app context
public SoundManager(Context appContext)
{
mySound = new SoundPool(16, AudioManager.STREAM_MUSIC, 100);
pContext = appContext;
}
// Load up a sound and return the id
public int load(int sound_id)
{
return mySound.load(pContext, sound_id, 1);
}
// Play a sound
public void play(int sound_id)
{
mySound.play(sound_id, leftVolume, rightVolume, 1, 0, rate);
}
// Set volume values based on existing balance value
public void setVolume(float vol)
{
masterVolume = vol;
if(balance < 1.0f)
{
leftVolume = masterVolume;
rightVolume = masterVolume * balance;
}
else
{
rightVolume = masterVolume;
leftVolume = masterVolume * ( 2.0f - balance );
}
}
public void unloadAll()
{
mySound.release();
}
}
The method play() return a int StreamId. You need to keep this StreamId on a variable and to call the stop method. For example:
Declare a Stream Id variable:
private int mStreamId;
Then, keep it when you start a new sound stream:
// Play a sound
public void play(int sound_id)
{
mStreamId = mySound.play(sound_id, leftVolume, rightVolume, 1, 0, rate);
}
So you can stop it doing:
mySound.stop(mStreamId);
Now you can stop your sound stream on the activities events onStop, onPause or where you want.
EDIT:
The best way to release your SoundPool resource is call release and set the reference to null after you stop playing the sound. For example:
#Override
protected void onPause() {
super.onPause();
mSoundManager.unloadAll();
}
On your SoundManager, change your unloadAll method to:
public void unloadAll()
{
mySound.release();
mySound = null;
}
Note the following:
onPause – is always called when the activity is about to go into the
background.
release: releases all the resources used by the SoundPool
object null: this SoundPool object can no longer be used (like #DanXPrado
said) so set it to null to help the Garbage Collector identify it as
reclaimable.
For more details, see this tutorial about SoundPool.
Hope this helps.

How can I play sound when my activity starts

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.textView1);
view.setOnTouchListener(this);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundID = soundPool.load(this, R.raw.dog_bark, 1);
}
;
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
}
}
return false;
}
}
I tried this way, but the sound is being played on touch event. I want the sound to be played automatically when my activity starts. But it should stop after a loop is completed and start again on touch event. Please help.
Use this in the activity where you wanna hear the music
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.sound1);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
public class CommonMethod {
public static MediaPlayer player;
public static void SoundPlayer(Context ctx,int raw_id){
player = MediaPlayer.create(ctx, raw_id);
player.setLooping(false); // Set looping
player.setVolume(100, 100);
//player.release();
player.start();
}
}
//you can use this method for stopping the player.
CommonMethod.player.stop();
If it because you are just loading the sound on onCreate() and play it on touch!
Try soundPlay.play() in onCreate instead!
you can play the sound in a runnable and post it in onCreate method.
View view = findViewById(R.id.textView1);
view.post(new Runnable() {
#Override
public void run() {
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
}
}
});
Put your onTouch() method's code into OnStart() method of your Activity, so that when activity is started, then Your sound plays.
If your activity name is MainActivity
MediaPlayer play= MediaPlayer.create(MainActivity.this,R.raw.sound);
play.start();
Place this in the onCreate method

Timer interrupt MediaPlayer

In my activity there is a timer which send a message to a handler every second which changes a picture.
Every time user clicks the image a sound is played in onClickListner function of activity using this code:
MediaPlayer.create(this, R.raw.voice).start();
On a xperia arc (Android 4.0.4) the sound is not completely played and as soon as the timer triggers it stops. If I disable the timer there is no problem.
On a HTC Legend (Android 2.2) there is no problem. The sound is played completely.
I can't figure out the problem.
public class ActivityTest extends Activity implements View.OnClickListener, ViewSwitcher.ViewFactory
{
ImageSwitcher switcher;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test_listen);
switcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
switcher.setFactory(this);
switcher.setOnClickListener(this);
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
switcher.setImageDrawable(getResources().getDrawable(R.drawable.image));
// if this line is commented it works fine
}
};
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run()
{
handler.sendEmptyMessage(0);
}
}, 0, 1000);
}
#Override
public void onClick(View view)
{
MediaPlayer.create(this, R.raw.voice).start();
}
#Override
public View makeView()
{
ImageView image = new ImageView(this);
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setLayoutParams(new ImageSwitcher.LayoutParams(ImageSwitcher.LayoutParams.FILL_PARENT, ImageSwitcher.LayoutParams.FILL_PARENT));
return image;
}
}
Solution -------------------------------------
I moved the declaration of MediaPlayer to class and it fixed the problem.
MediaPlayer mp;
#Override
public void onClick(View view)
{
mp =MediaPlayer.create(this, R.raw.voice);
mp.start();
}
I don't know why the previous code works on 2.2 but not 4. anyway it worked.
since its a short sound your playing i'd recommend a soundpool. Soundpool clips are kept in memory for quick access since there small. Im assuming your playing a very short sound. in onCreate do this to preload it:
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundID= soundPool.load(this, R.raw.voice, 1);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
then in the onclick method (when user clicks the image) do this:
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
}
where soundPool is declared as a instance variable private SoundPool soundPool or something similar. Try that and let me know what happens.

Categories

Resources