I am searching for a long time on net, and many answers advised to use the setVolume in MediaPlayer.OnPreParedListener, it works when I use it before MediaPlayer.start().
But now there is a button, I want to control mute or unmute when the video is playing, so how to resolve it?
Use this code
private static int aux = 0;
private Button mMuteButton;
private static int aux = 0;
private AudioManager mAudioManager;
//set the Mute button on clickListener inside the class android cycle where needed
mMuteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if(aux % 2 == 0){
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
aux++;
} else {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
aux++;
}
}
});
Related
I'm working on an app that needs to play the system notification at different volume levels and have some issues with getting setVolume to work properly.
To debug this, I prepared a sample app with two buttons that allows me to play the system notification at a low or a high volume. So far, the app works, and the sound comes out of the speaker.
However, no matter in which sequence I press the low and high volume buttons, once I have played the notification at a low volume, it stays low, I can't get it to play at the higher volume again.
Below is my code. I used an oncompletion callback to increment a counter and sound the notification 3 times.
public class MainActivity extends AppCompatActivity {
int soundsCounter = 0; // Counts how many times the notification has sounded
double playbackVolume = 1.0; // Playback volume of the notification
AudioManager audioManager;
MediaPlayer thePlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setup the media player
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
thePlayer = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
// Initialize listener using setOnCompletionListener for mediaPlayer object
// and declare new method OnComletionListener as an argument.
thePlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
// Override onCompletion method to apply desired operations.
#Override
public void onCompletion(MediaPlayer mediaPlayer){
soundsCounter++;
if (soundsCounter < 3){ // Sound the notification 3 times
playNotification();
}
}
} );
}
// Plays system notification at the selected volume
private void playNotification() {
try {
thePlayer.setVolume(((float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) * playbackVolume)),
(float) (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) * playbackVolume));
}
thePlayer.start();
}
// Called when the user taps the HighV button
public void playHighV(View view) {
soundsCounter = 0;
playbackVolume = 1.0;
playNotification();
}
// Called when the user taps the LowV button
public void playLowV(View view) {
soundsCounter = 0;
playbackVolume = 0.02;
playNotification();
}
Any ideas where to look? Thanks!
Thanks to Oemel09 I realized I was making some mistakes in the parameters passed to setVolume.
Here's the new code that works fine:
public class MainActivity extends AppCompatActivity {
int soundsCounter = 0; // Counts how many times the notification has sounded
float playbackVolume = 1; // Playback volume of the notification
AudioManager audioManager;
MediaPlayer thePlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setup the media player
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
thePlayer = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
// Initialize listener using setOnCompletionListener for mediaPlayer object
// and declare new method OnComletionListener as an argument.
thePlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
// Override onCompletion method to apply desired operations.
#Override
public void onCompletion(MediaPlayer mediaPlayer){
soundsCounter++;
if (soundsCounter < 3){ // PLay sound 3 times
playNotification();
}
}
} );
}
// Plays system notification at the selected volume
private void playNotification() {
thePlayer.setVolume(playbackVolume, playbackVolume);
thePlayer.start();
}
// Called when the user taps the HighV button
public void playHighV(View view) {
soundsCounter = 0;
playbackVolume = 1f;
playNotification();
}
// Called when the user taps the LowV button
public void playLowV(View view) {
soundsCounter = 0;
playbackVolume = 0.1f;
playNotification();
}
}
I am using Android's MediaPlayer to loop audio files. I set the media player looping with
mMediaPlayer.setLooping(true);
After several repetitions, the loop starts earlier than it should do i.e. if I play the same loop on a computer, with a metronome running independently at the same BPM as the loop, Android's Media player and metronome stay synced for a few bars, but after a couple of loop, the loop played with the app starts too early.
I've read about other peoples complaining about this problem.
I reproduce this problem both on Android 4.4 and Android 6
Here is a minimal Android project for reproducing the problem:
https://drive.google.com/open?id=0B9FRLIzBQgR1WWdMU29ZcHdsMXc
In my project, I had the same issue and I found he solution in SO somewhere, I don't remember exactly where. But here what I've done:
You can try using a handler to set seek to beginning x milliseconds before the end of file
loopTimer = new Timer();
loopTask = new TimerTask() {
#Override public void run() {
mMediaPlayer.seekTo(0);
}
};
long waitingTime = mMediaPlayer.getDuration()-mLoopingPreview;
loopTimer.schedule(loopTask, waitingTime, waitingTime);
Now just set mLoopingPreview to some reasonable time value. I'm using 80ms.
I also faced this problem...in Mediaplayer
There is couple of solution:
1.use ogg format sound file (https://en.wikipedia.org/wiki/.ogg)
2.Can use soundpool it has a looping and caching facility for media play (https://developer.android.com/reference/android/media/SoundPool.html)
3.Also you can use the following class: it initialize a new mediaplayer as soon as the first one finishes..so the delay is less more obvious
public class LoopMediaPlayer {
public static final String TAG = LoopMediaPlayer.class.getSimpleName();
private Context mContext = null;
private int mResId = 0;
private int mCounter = 1;
private MediaPlayer mCurrentPlayer = null;
private MediaPlayer mNextPlayer = null;
public static LoopMediaPlayer create(Context context, int resId) {
return new LoopMediaPlayer(context, resId);
}
private LoopMediaPlayer(Context context, int resId) {
mContext = context;
mResId = resId;
mCurrentPlayer = MediaPlayer.create(mContext, mResId);
mCurrentPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mCurrentPlayer.start();
}
});
createNextMediaPlayer();
}
private void createNextMediaPlayer() {
mNextPlayer = MediaPlayer.create(mContext, mResId);
mCurrentPlayer.setNextMediaPlayer(mNextPlayer);
mCurrentPlayer.setOnCompletionListener(onCompletionListener);
}
private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
mCurrentPlayer = mNextPlayer;
createNextMediaPlayer();
Log.d(TAG, String.format("Loop #%d", ++mCounter));
}
};
}
to use it just call
LoopMediaPlayer.create(context, R.raw.sound_file_name);
instead of mp.setLooping(true);
I have problem with my application
I have a main layout: main.xml, it includes a button named "Setting"
When I click the Setting button,
I use setContentView(R.layout.setting); to go to the setting.xml
In setting.xml, I have a seekbar to control the volume of app
I have followed this post "Using SeekBar to Control Volume in android?"
I do like this in my activity_main, but nothing happens when i change the seekbar
Here is the code:
//control volume using seek bar in Setting
private AudioManager audiomanager = null;
private SeekBar seekbar = null;
// SoundStatus
private TextView soundstatus = null;
// check Sound on
private boolean soundon = true;
// control Background Sound
private MediaPlayer mp = null;
// Sound icon
private ImageView sound = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.activity_main);
// Background music when the app launch
// music in raw folder
mp = MediaPlayer.create(this, R.raw.backgroundsound);
mp.start();
mp.setLooping(true);
// Control volume
ControlVolume();
}
...
...
...
public void ControlVolume()
{
seekbar = (SeekBar)findViewById(R.id.seekBar);
audiomanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audiomanager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekbar.setProgress(audiomanager
.getStreamVolume(AudioManager.STREAM_MUSIC));
seekbar.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);
}
});
}
this is MainActivity.java
main layout include button setting
and the seekbar is in setting layout
I have a simple activity which contains one instance of a VideoView and a reference to its' MediaPlayer. My goal was to use the setNextMediaPlayer() api from the MediaPlayer object in order to minimize the switching time between 2 videos.
In the below code, the 1st video plays well. When the 1st video completes, the 2nd video's audio begins to play in the background, but only the last frame of the 1st video is shown.
Do you know what the problem is? Why isn't the 2nd video's video displaying?
private VideoView player1;
private MediaPlayer mediaPlayer1;
public static final String URL_1 = "https://example.com/video1.mp4";
public static final String URL_2 = "https://example.com/video2.mp4";
public static final String TAG = "PrebufferingActivity";
public boolean FIRST_TIME = true;
public int count = 0;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prebuffering);
player1 = (VideoView) findViewById(R.id.videoPlayer1);
player1.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer1 = mp;
if(FIRST_TIME == true)
{
mediaPlayer1.start();
player1.requestFocus();
FIRST_TIME = false;
}
}
});
player1.setOnInfoListener(new OnInfoListener(){
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
{
if(what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
{
count++;
if(count % 2 != 0)
{
Log.d(TAG, "Odd count (" + count + ") Prebuffering URL_2");
MediaPlayer myMediaPlayer = MediaPlayer.create(PrebufferingActivity.this, Uri.parse(URL_2));
mp.setNextMediaPlayer(myMediaPlayer);
}
else
{
Log.d(TAG, "Even count (" + count + ") Prebuffering URL_1");
MediaPlayer myMediaPlayer = MediaPlayer.create(PrebufferingActivity.this, Uri.parse(URL_1));
mp.setNextMediaPlayer(myMediaPlayer);
}
}
return false;
}
});
player1.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mp) {
}
});
// Player 1
player1.setMediaController(new MediaController(this));
player1.setVideoURI(Uri.parse(URL_1));
}
In your example you create new MediaPlayer, but VideoView knows nothing about and can't control it. It wouldn't work properly.
If you need some specific functions probably you need to build your analog of VideoView, that would use MediaPlayer.
Regarding playing 2nd video by using setNextMediaPlayer() you can find some hints here:
https://stackoverflow.com/a/28465846/755313
I have soundpool that will load file from sd-card and I used mstreamID to stop it and I use mstreamID in OnLoadCompleteListener so the files can load. I use 2 buttons to play soundpool diffrent sounds. But when I click first button and while it plays 1 sound I click second button and it stops the sound from first button.
Here is my code:
public class MainActivity extends Settings {
SoundPool mSoundPool;
int mSoundId;
int mStreamId = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
mSoundPool
.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool,
int sampleId, int status) {
mStreamId = soundPool.play(sampleId, 1, 1, 1, 0, 1f);
}
});
}
//OnClick
public void button1(View view) {
if (mStreamId != 0) {
mSoundPool.stop(mStreamId);
}
// et1 is extended from Settings.java
String path = getFullFilePath(getApplicationContext(), et1.getText()
.toString());
mSoundId = mSoundPool.load(path, 1);
}
public void button2(View view) {
if (mStreamId != 0) {
mSoundPool.stop(mStreamId);
}
String path = getFullFilePath(getApplicationContext(), et2.getText()
.toString());
mSoundId = mSoundPool.load(path, 1);
}
Read doc please, and what is the thing you want to say?
do not load same file more than one time if you not unload it.
load all sound at start when use SoundPool.
streamId is increasing all the time, you never get same streamId.