Play Sound OnClick Android - android

I simply want to play a mp3 file when I click a button in android studio.
My problem is that with the 2 methods I use the sound is played but for some reason, I hear it like an extremely distorted super slow motion sound. While if I normally open the file it is ok.
!!!!!METHOD 1:
I declared:
SoundPool mySound;
int soungId;
I initialize:
mySound = new SoundPool(1, AudioManager.STREAM_MUSIC,0);
soungId = mySound.load(this, R.raw.asd,1);
Then is use an action listener:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mySound.play(soungId,1,1,1,0,1);
}
});
!!!!!METHOD 2:
I declare:
MediaPlayer mp = null;
I use listener:
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
managerOfSound();
}
});
My managerOfSound mathod :
public void managerOfSound() {
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, R.raw.www);
mp.reset();
mp.start();
}

It may be because the Soundpool instance of the MaxStreams maximum number (maximum number of concurrent streams) is too low
SoundPool mySound;
mySound = new SoundPool(10, AudioManager.STREAM_MUSIC,0);

try this,
MediaPlayer mp = new MediaPlayer();
// Set data source -
setDataSource("/sdcard/path_to_song");
// Play audio
mp.start();
// Pause audio
mp.pause();
// Reset mediaplayer
mp.reset();
// Get song length duration - in milliseconds
mp.getDuration();
// Get current duration - in milliseconds
mp.getCurrentDuration();
// Move song to particular second - used for Forward or Backward
mp.seekTo(positon); // position in milliseconds
// Check if song is playing or not
mp.isPlaying(); // returns true or false
http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/

Related

Mediaplayer - stop current audio when clicking on new audio

Im a newbie to android studio (programming at general) but i want to build a mediaplayer for learning purposes.
I have a a list of local music in a listView that contains 2 images 'play, pause and stop button'.
This is how my app works:
Click on playbutton -> start music
Click on pausebutton -> pause music
Click on stopbutton -> stop music
Very simple. BUT! the thing is -> when i pause a song and want to play another song in my list then it just resume the first song i clicked on.
I want it to release the first song and start the other one i click on.
This is my code:
// play music
viewHolder.playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (flag) {
//get song you clicked on
mediaPlayer = MediaPlayer.create(context, song.getSong());
//set boolean to false so it can get ANOTHER song when
//clicked
flag = false;
Toast.makeText(context, "Playing" + song.getName(),
Toast.LENGTH_LONG).show();
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewHolder.playB.setImageResource(R.drawable.play);
} else {
mediaPlayer.start();
viewHolder.playB.setImageResource(R.drawable.pause);
}
}
});
// stop
viewHolder.stopB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!flag) {
mediaPlayer.stop();
mediaPlayer.release();
flag = true;
}
viewHolder.playB.setImageResource(R.drawable.play);
}
});
Your logic is a little bit wrong. When you create the MediaPlayer you set flag to false and as long as you do not stop playback flag doesn't change. But your MediaPlayer creation depends on it.
For future improvements (maybe when you're more confident in working with MediaPlayer and Android) you should take a look at a more "self-made" approach instead of MediaPlayer.create(...) cause this method is calling MediaPlayer's prepare() method that is going to eventually make your app extremely slow or crash it when loading big files.
Example according to comments
I assumed songis going to be the class object.
// class variable will hold the currently loaded song
private Song mCurrentSong;
[...]
viewHolder.playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// MediaPlayer has not been initialized OR clicked song is not the currently loaded song
if (mCurrentSong == null || song != mCurrentSong) {
// Sets the currently loaded song
mCurrentSong = song;
mediaPlayer = MediaPlayer.create(context, song.getSong());
Toast.makeText(context, "Playing" + song.getName(),
Toast.LENGTH_LONG).show();
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewHolder.playB.setImageResource(R.drawable.play);
} else {
mediaPlayer.start();
viewHolder.playB.setImageResource(R.drawable.pause);
}
}
});
viewHolder.stopB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// If currently loaded song is set the MediaPlayer must be initialized
if (mCurrentSong != null) {
mediaPlayer.stop();
mediaPlayer.release();
mCurrentSong = null; // Set back currently loaded song
}
viewHolder.playB.setImageResource(R.drawable.play);
}
});

Play a custom sound after some time when a key pressed on android custom keyboard

I want to play a sound (custom, not system default) after some seconds when a key is pressed. I got a countdown timer running on the key. So want to play a sound onFinish function.
my code for that key is:
if(isCountDownRunning)
return;
isCountDownRunning = true;
new CountDownTimer(14000, 1000) {
public void onTick(long millisUntilFinished) {
keyboard.getKeys().get(0).label = millisUntilFinished / (1000) + "";
kv.invalidateKey(0);
}
public void onFinish() {
isCountDownRunning = false;
keyboard.getKeys().get(0).label ="ADV";
kv.invalidateKey(0);
}
}.start();
break;
You can add the custom sound in a folder res/raw/ . Then use MediaPlayer to play sound like,
MediaPlayer mMediaPlayer = MediaPlayer.create(this, rid);//rid -->R.raw.customsound
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mMediaPlayer.stop();
}
});
want to play a sound onFinish function
In your onFinish function, add this line
mMediaPlayer.start();

mediaplayer gets hanged

My list consists of 12 songs and it has to move in an infinite loop when the button is clicked.my mediaplayer is working fine in emulator but it is getting stuck if i press the button continuously for 32 times in htc mobile.
public void onClick(View v)
{
if(count==listlen)
count=-1;
if(count<listlen)
{
count=count+1;
}
loadpitch(concatstr);
}
load pitch has this
try
{
if(sp.isChecked()||sm.isChecked())
{
mp.reset();
mp=MediaPlayer.create(this,resID);
mp.setLooping(true);
}
if(play==true)
{
mp.start();
}
}
where listlen is the length of the pre-defined list
loadpitch is function which loads the song
sp and sm are toggle buttons!
check this way for ur media player while starting media player onclick
if (mPlayer!=null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer= MediaPlayer.create(YourActivity.this,song);
mPlayer.start();

Playing a WAV File Multiple Times

I need to have the same short wav file (1 second) play each time the user presses a single button. I have the following code that works for about 30 clicks and then the app "Force closes" on the device. I think what is going on is that new instances of media player are being created and then the instances build up (approx 30 clicks) and the app crashes. So I then added the "release" instance in the hope that on button-click the wav would play and then the mediaplayer would be released. However, it doesnt work that way. With the mp.release() no sound is played possibly becaue the medaiplayer gets released too soon for the user to hear the sound?
Anyone have a good tip to help me getting this to work? Thank you all so much.
Button button2 = (Button) findViewById(R.id.button10);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.clicker);
mp.start();
mp.release();
Its simple just create the MediaPlayer once, and play it over time.
private MediaPlayer mp;
public void onClick(View v) {
// Perform action on click
if (mp == null){
mp = MediaPlayer.create(getApplicationContext(), R.raw.clicker);
}
mp.start();
}
Why use MediaPlayer, when SoundPool is better suited for small audio files? As a base you could use this:
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 70);
final HashMap<Integer, Integer> soundPoolMap = new HashMap<Integer, Integer>();
final int soundID = 4;
soundPoolMap.put(soundID, soundPool.load(this, R.raw.wav_sound, 4));
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener()
{
public void onLoadComplete(SoundPool soundPool, int sampleId, int status)
{
if (sampleId == 4)
{
soundPool.play(4, 50, 50, 1, 0, 1f);
}
}
});
Here is the simple solution that will work
MediaPlayer mp;
mp = MediaPlayer.create(getApplicationContext(), R.raw.clicker);
public void onClick(View v) {
// Perform action on click
if(mp.isPlaying())
{
mp.stop();
mp.reset();
mp.release();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.clicker);
mp.start();
This is will check if mediaplayer is already playing..If it already playing it will stop and release it and then initialize that mediaplayer(mp) object and start the mediaplayer.
If it is not playing it will execute the code after the if statement and the start the media player after initialzing the mediaplayer object(mp in this case)
To learn more about MediaPlayer study this http://developer.android.com/reference/android/media/MediaPlayer.html. Study the Mediaplayer life cycle

Android: Playing an audio clip onClick

How do I set up an audiofile to play when a user touches an image.
Where should I store the audio file and what code should I use to actually play the file?
I don't want to bring up the MediaPlayer interface or anything like that.
I was thinking of doing it like this:
foo = (ImageView)this.findViewById(R.id.foo);
foo.setOnClickListener(this);
public void onClick(View v) {
if (foo.isTouched()) {
playAudioFile();
}
}
Thanks
This won't create a bring up the MediaPlayer interface... it will just play the sound you want.
Button boton = (Button) findViewById(R.id.boton);
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(TestSonido.this, R.raw.slayer);
mp.start();
}
});
In this case, R.raw.slayer represents an audio file called slayer.mp3 that is stored in the res/raw/ folder and once you click the button the droid will rock you...
You can also achieve the same using SoundPool.
MediaPlayer first loads the whole sound data in memory then play, so it produces some lag when we switch among sounds frequently.
SoundPool is a better option with small size sound file and produces better result with .ogg media file.
SoundPool pl = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
// 5 indicates the maximum number of simultaneous streams for this SoundPool object
pl.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
// The onLoadComplet method is called when a sound has completed loading.
soundPool.play(sampleId, 1f, 1f, 0, 0, 1);
// second and third parameters indicates left and right value (range = 0.0 to 1.0)
}
});
Button btn = findViewById(R.id.boton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sound = pl.load(this, R.raw.sound_01, 0);
}
});
public void aud_play(View view) {
if (!mp.isPlaying()) { //If media player is not playing it.
mp = MediaPlayer.create(this, R.raw.audio_name);
mp.start();
} else {// Toast of Already playing ...
}
}

Categories

Resources