how to set two or three times ringing sound? - android

I set custom dingdong bell sound but it ring one time . how to set two or three times ringing sound.
Here java Code,
mMediaPlayer = new MediaPlayer();
mMediaPlayer =
MediaPlayer.create(MyRideDetailTrackRide.this, R.raw.dingdong);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mMediaPlayer.setLooping(true);
mMediaPlayer.start();

int howManyTimesPlayed = 0;
mediaPlayer.setOnCompletionListener(new OnCompletionListener(){
int maxRePlayCount = 3; // set this value to replay x time
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if(howManyTimesPlayed < maxRePlayCount) {
howManyTimesPlayed++;
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
}});

Related

How to syncronize system volume with mediaplayer app

I've just developed a simple media player that sounds a song and it has a seekbar that regulate the song volume.
That's my code:
public class MainActivity extends AppCompatActivity {
Button playBtn;
SeekBar positionBar;
SeekBar volumeBar;
TextView elapsedTimeLabel;
TextView remainingTimeLabel;
MediaPlayer mp;
int totalTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (Button) findViewById(R.id.playBtn);
elapsedTimeLabel = (TextView) findViewById(R.id.elapsedTimeLabel);
remainingTimeLabel = (TextView) findViewById(R.id.remainingTimeLabel);
// Media Player
mp = MediaPlayer.create(this, R.raw.song);
mp.setLooping(true);
mp.seekTo(0);
mp.setVolume(0.5f, 0.5f);
totalTime = mp.getDuration();
// Position Bar
positionBar = (SeekBar) findViewById(R.id.positionBar);
positionBar.setMax(totalTime);
positionBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
positionBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
// Volume Bar
volumeBar = (SeekBar) findViewById(R.id.volumeBar);
volumeBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float volumeNum = progress / 100f;
mp.setVolume(volumeNum, volumeNum);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
// Thread (Update positionBar & timeLabel)
new Thread(new Runnable() {
#Override
public void run() {
while (mp != null) {
try {
Message msg = new Message();
msg.what = mp.getCurrentPosition();
handler.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}).start();
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int currentPosition = msg.what;
// Update positionBar.
positionBar.setProgress(currentPosition);
// Update Labels.
String elapsedTime = createTimeLabel(currentPosition);
elapsedTimeLabel.setText(elapsedTime);
String remainingTime = createTimeLabel(totalTime-currentPosition);
remainingTimeLabel.setText("- " + remainingTime);
}
};
public String createTimeLabel(int time) {
String timeLabel = "";
int min = time / 1000 / 60;
int sec = time / 1000 % 60;
timeLabel = min + ":";
if (sec < 10) timeLabel += "0";
timeLabel += sec;
return timeLabel;
}
public void playBtnClick(View view) {
if (!mp.isPlaying()) {
// Stopping
mp.start();
playBtn.setBackgroundResource(R.drawable.ic_stop);
} else {
// Playing
mp.pause();
playBtn.setBackgroundResource(R.drawable.ic_play);
}
} }
Now, when I regulate the volume with the media player seekbar, the phone system volume didn't change and the other way around.
How can I syncronize the volume seekbar with the phone system volume so as to adjust the volume with both?
Using the Audio Manager to Raise and Down Volume.
AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
//Using volume control UI visibility
//To increase media player volume
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
//To decrease media player volume
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
//Without volume control UI
//To increase media player volume
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
//To decrease media player volume
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);

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

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