How to play audio on button click (recycler view) - android

How do I play an audio from raw folder on button click? Here, I'm using recyclerview to show the list of audios. But when click play, it doesn't play any sound.
private Button btnPlay;
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = new MediaPlayer();
try{
mp.setDataSource(ss.getSoundURI());
mp.prepare();
mp.start();
} catch (Exception e){
e.printStackTrace();
}
}
});

You can use this function:
public void playSound(final String fileName) {
MediaPlayer mpPlayer = null;
try {
int fileId = getResources().getIdentifier(fileName, "raw", getPackageName());
mpPlayer = MediaPlayer.create(this, fileId);
mpPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mpPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} catch (Exception e) {
e.printStackTrace();
if (mpPlayer != null)
mpPlayer.release();
}
}
NOTE: use file name without file extension. for example if your file name is file1.wav you should send file1 as a file name to function NOT file1.wav .
NOTE: In first line I defined the mpPlayer and initialize it because i want to use it in the catch block.

Related

Play audio from url one after other

I want to play/stream audio from url one after other automatically.
here what I have tried:
final String audioUrl[] = {"https://www.googleapis.com/storage/v1/b/ezconnectpoc/o/NV.wav?alt=media", "https://www.googleapis.com/storage/v1/b/ezconnectpoc/o/cqo.wav?alt=media"};
backtobackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(audioUrl[currentTrack]);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
try {
Log.d("Current track",currentTrack+"");
Log.d("audioUrl.length",audioUrl.length+"");
if (currentTrack < audioUrl.length) {
currentTrack++;
mediaPlayer.setDataSource(audioUrl[currentTrack]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
mediaPlayer.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
// make something
}
}
});
My first audio url gets played when I click on backtoback named button but failed to play second audio from url.
changed this part of code
mediaPlayer.reset();
mediaPlayer.setDataSource(audioUrl[currentTrack]);
mediaPlayer.prepareAsync();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
currentTrack++;
and worked.

make click sound when pressing a button

Where should I add the button.playSoundEffect(SoundEffectConstants.CLICK); ?
Should it be here:
//onClick event where myButton1 is pressed a click sound occurs
public void onClick(View v){
if (v.getId() == R.id.b_Press1){
myButton1.playSoundEffect(SoundEffectConstants.CLICK);
}
1) You should put mp3 file in /raw folder.
2) Put this code inside onCreate() method after setContentView()
final MediaPlayer mp = new MediaPlayer();
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
mp.reset();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("AudioFile.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
3.Sound will be played again each time you press button. You don't have to write any extra code for that.
Note that AudioFile.mp3 is the name of the mp3 file in /raw folder
Hope this answer is helpful:)
The sound effect will only be played if sound effects are enabled by the user, and isSoundEffectsEnabled() is true.
so make sure you enable it using xml like
android:soundEffectsEnabled="true"
or
through code
myButton1.setSoundEffectsEnabled(true)
try it out
final MediaPlayer mp = new MediaPlayer();
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
mp.reset();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("song.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
use this code. for more information read this link1 and link2
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
button.playSoundEffect(0);
}
});
You don't need to call playSoundEffect() for clicks yourself. From the docs:
The framework will play sound effects for some built in actions, such as clicking
Also note:
The sound effect will only be played if sound effects are enabled by the user

Android Media Player Replay Option

How can i replay a .mp3 in my app? I can't replay the mp3 using the start method
Here is the code segment :
mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.splashsound);
mMediaPlayer.setLooping(true);
Button myButtonOne = (Button) findViewById(R.id.songon);
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mMediaPlayer.start();
}
});
Button myButtonTwo = (Button) findViewById(R.id.songoff);
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mMediaPlayer.isPlaying()){
//mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
});
Can anyone please tell me what i am doing wrong here?
If you want to replay the mp3 why do release and set to null your media player?
I guess that is your problem!
Just stop and start it again without releasing your media player instance.
To replay mp3 track try this:
private void playSong(int songIndex) {
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Or without calling reset():
mediaPlayer.setLooping(true);

adding mutiple audio file in android

i'm adding multiple audio files using
try {
MediaPlayer mp = MediaPlayer.create(context, R.raw.play);
audioArr[0] = mp;
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
and releasing media in a function as
for (MediaPlayer media : audioList) {
if (media != null) {
if(media.isPlaying())
media.stop();
media.release();
media = null;
}
}
stil i'm not able to play multiple audio file in my application,first time playing with audio,so kindly guide
Try this :
void addSongs()
{
File songs = new File(sdPath); //sdPath is the path of your audio files
if(songs.listFiles(new SongFilter()).length > 0)
{
for(File file : songs.listFiles(new SongFilter()))
{
vector.add(file.getName());
}
arrayAdapter.setNotifyOnChange(true); //arrayAdapter Array Adapter
songList.setAdapter(arrayAdapter); //songList is a ListView
}
}
SongFilter Class like this :
class SongFilter implements FilenameFilter
{
public boolean accept(File dir, String filename)
{
return (filename.endsWith(".mp3"));
}
}
buttonSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// play another sound here.do your stuff whatever you want to do
mp.stop();
}
});
public class AudioActivity extends Activity implements MediaPlayer.OnCompletionListener {
int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {##}
private void start(){
songs= new int[] {R.raw.s1,R.raw.s2,R.raw.s3,R.raw.s4};
mediaPlayer = MediaPlayer.create(this, songs[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
**// This is the completion listener registered with mediaplayer instance.**
playNextSong();
}
private void playNextSong()
{
current_index = (current_index +1)% songs.length;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);
if(current_index!=0){
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e){}
catch (IllegalStateException e){}
catch (IOException e){}
}else{
mediaPlayer.stop();
}
}
}

Playing audio files one after another

I have a list of audio files like this,
int music_numbers[] = { R.raw.one, R.raw.two, R.raw.three, R.raw.four,
R.raw.five, R.raw.six, R.raw.seven, R.raw.eight, R.raw.nine };
I need to play this one by one - when i send 100 to this play_numbers method - i am intend to play digit wise..
I have done this - but i unable to do this one after another..
private void _play_numbers(final String i) {
// TODO Auto-generated method stub
mPlayer = MediaPlayer.create(PlayFileActivity.this, R.raw.payment);
mPlayer.start();
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mPlayer.stop();
myDigit = i.charAt(1) + "";
_function_play_file(Integer.parseInt(myDigit));
}
});
}
in _function_play_file - i have this
void _function_play_file(int files) {
switch (files) {
case 0:
mPlayer = MediaPlayer.create(this, music_numbers[0]);
mPlayer.start();
case 1:
mPlayer = MediaPlayer.create(this, music_numbers[1]);
mPlayer.start();
case 2:
mPlayer = MediaPlayer.create(this, music_numbers[2]);
mPlayer.start();
case 3:
mPlayer = MediaPlayer.create(this, music_numbers[3]);
mPlayer.start();
case 4:
mPlayer = MediaPlayer.create(this, music_numbers[4]);
mPlayer.start();
case 5:
mPlayer = MediaPlayer.create(this, music_numbers[5]);
mPlayer.start();
case 6:
mPlayer = MediaPlayer.create(this, music_numbers[6]);
mPlayer.start();
case 7:
mPlayer = MediaPlayer.create(this, music_numbers[7]);
mPlayer.start();
case 8:
mPlayer = MediaPlayer.create(this, music_numbers[8]);
mPlayer.start();
case 9:
mPlayer = MediaPlayer.create(this, music_numbers[9]);
mPlayer.start();
case 10:
mPlayer = MediaPlayer.create(this, music_numbers[10]);
mPlayer.start();
}
}
You need to set an onCompletionListener to each and start the next one on completion.
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// Code to start the next audio in the sequence
}
});
The best way to achieve this is to create a class that implements OnCompletionListener which handles the onCompletion and receives the next file to play. This way you can instantiate it nicely in your code.
Of course, don't forget your break; in the cases above.
Use a queue for holding the numbers to be played.
private void _play_numbers(final String i) {
// e.g '100': put '1', '0', '0' in a Queue after converting to digits
Queue queue = new LinkedList();
//Use the add method to add items.
myDigit = // remove next digit from queue..
_function_play_file(myDigit);
}
void _function_play_file(int files) {
switch(files) {
case 0:
mPlayer = MediaPlayer.create(PlayFileActivity.this, R.raw.payment);
mPlayer.setOnCompletionListener(completeListener );
mPlayer.start();
break;
.....
}
OnCompletionListener completeListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
myDigit = // remove next digit from queue..
if (myDigit != -1) // if queue is not empty..
_function_play_file(myDigit);
}
});
}
This code works for me,but i place the audio files in assets folder:
//define a variable to be used as index.
int audioindex = 0;
//Extract the files into an array
String[] files = null;
files = assetManager.list("audiofiles");
mp.setOnCompletionListener(new OnCompletionListener(){
// #Override
public void onCompletion(MediaPlayer arg0) {
// File has ended, play the next one.
FunctionPlayFile(files[audioindex]);
audioindex+=1; //increment the index to get the next audiofile
}
});
This is working code for playing songs in continue loop
public class MainActivity extends Activity
{
private int[] tracks = {R.raw.explosion,R.raw.pianothingy_one,R.raw.car_horn_x};
int mCompleted = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = MediaPlayer.create(this, tracks[0]);
mp.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mCompleted++;
mp.reset();
if (mCompleted < tracks.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted>=tracks.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp.release();
mp = null;
}
}
});
mp.start();
use PlayMedia Like this
int[] soundIDs = {R.raw.yes, R.raw.eat};
PlayMedia playAudio = new PlayMedia(context,soundIDs);
playAudio.execute();
and define PlayMedia Class Like this
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.util.Log;
public class PlayMedia extends AsyncTask<Void, Void, Void> {
private static final String LOG_TAG = PlayMedia.class.getSimpleName();
Context context;
private MediaPlayer mediaPlayer;
int[] soundIDs;
int idx =1;
public PlayMedia(MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
}
public PlayMedia(final Context context, final int[] soundIDs) {
this.context = context;
this.soundIDs=soundIDs;
mediaPlayer = MediaPlayer.create(context,soundIDs[0]);
setNextMediaForMediaPlayer(mediaPlayer);
}
public void setNextMediaForMediaPlayer(MediaPlayer player){
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if(soundIDs.length>idx){
mp.release();
mp = MediaPlayer.create(context,soundIDs[idx]);
setNextMediaForMediaPlayer(mp);
mp.start();
idx+=1;
}
}
});
}
#Override
protected Void doInBackground(Void... params) {
try {
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "", e);
} catch (SecurityException e) {
Log.e(LOG_TAG, "", e);
} catch (IllegalStateException e) {
Log.e(LOG_TAG, "", e);
}
return null;
}
}
For me the issue was that I was calling mediaPlayer.prepare() without first calling mediaPlayer.reset().
All good now.
MediaPlayer mediaplayer = new MediaPlayer();
setSound(file );
try {
if(mediaplayer != null)
{
mediaplayer.stop();
mediaplayer.release();
}
mediaplayer.setDataSource(getResources().openRawResourceFd(file)
.getFileDescriptor());
mediaplayer.prepare();
mediaplayer = MediaPlayer.create(getBaseContext(), now);
mediaplayer.start();
mediaplayer.setLooping(false);
mediaplayer.setLooping(true); //sequence playing
} catch (NullPointerException e) {
e.printStackTrace();
}

Categories

Resources