how to stop Mediaplayer - android

I am having 3 tones. I am calling playmusic() function to play 2 of these tones on imageview toggle. when i click on imageview for first time tone1 starts playing. when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
my requiremet is , when i click on imageview for -
(1st time - tone1 should start playing).
(2nd time - tone1 should stop playing and tone2 should start playing)
(3rd time - tone2 should stop playing and tone1 should start playing again)
and so on....
String file=null;
int x=0;
public void playMusic(int i) {
x=i;
if(i==1){
file = R.raw.tone1;
}else if(i==2){
file = R.raw.tone2;
}else{
file = R.raw.tone3;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
Main2Activity.this.getResources().openRawResourceFd(file);
if(assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if(mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}

I did a small modification on your logic and added mediaplayer.reset(). Here is the solution link
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView player = findViewById(R.id.play);
player.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
playMusic(1);
}
});
mediaPlayer = new MediaPlayer();
}
int file = 0;
MediaPlayer mediaPlayer;
int x = 0;
public void playMusic(int i) {
x = x + i;
if (x == 1) {
file = R.raw.tone1;
}
else if (x == 2) {
file = R.raw.tone2;
} else {
x = 0;
file = R.raw.tone3;
}
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
MainActivity.this.getResources().openRawResourceFd(file);
if (assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
}

when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
If that's the only issue, try putting the following line before you call mediaPlayer = new MediaPlayer();:
if (mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();

Related

How to play and pause audio in firebase recyclerview in android

I am developing an app in which I have to fetch audio from firebase. I am using firebase recycler view. I am getting a problem that when I click the first song it plays good, but when I click second item then the first song's play button does not change and seekbar of first and second song changes.
Here is the code.
holder.play_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String audioUrl3 = model.getMedia();
if (!isPlaying){
if (mPlayer!=null){
mPlayer.release();
}
Toast.makeText(mContext, "Loading....", Toast.LENGTH_SHORT).show();
isPlaying = true;
Uri uri = Uri.parse(audioUrl3);
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.reset();
try {
mPlayer.setDataSource(mContext,uri);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mContext, "Error Occured", Toast.LENGTH_SHORT).show();
}
try{
mPlayer.prepareAsync();
}catch (Exception e){
Toast.makeText(mContext, "Error Occured", Toast.LENGTH_SHORT).show();
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_play));
}
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if(mPlayer.isPlaying()){
mPlayer.stop();
}
mPlayer.start();
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_pause));
holder.seekBar.setMax(mPlayer.getDuration());
Toast.makeText(mContext, "Playing...", Toast.LENGTH_SHORT).show();
updateSeekBar(holder.seekBar);
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_play));
isPlaying = false;
}
});
}
else {
isPlaying=false;
stopPlaying();
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer=null;
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_play));
}
});
}
private void updateSeekBar(final SeekBar seek) {
try{
int pos = mPlayer.getCurrentPosition();
seek.setProgress(pos);
}catch (Exception e){
}
runnable = new Runnable() {
#Override
public void run() {
updateSeekBar(seek);
}
};
handler.postDelayed(runnable, 1800);
}

I cant Play music that through MediaPlayer i have recorded

The Path where the file is located "/storage/sdcard/MediaRecorderSample/Recordingg2"
The errors i am getting
E/MediaPlayer: stop called in state 1,E/MediaPlayer: error (-38, 0),D/MediaPlayer: Couldn't open file on client side, trying server side
Here is my code
public class Player extends AppCompatActivity implements View.OnClickListener {
static MediaPlayer mp;
SeekBar sb;
ArrayList mysongs;
int pos;
Uri u;
Thread th;
String filepath;
File file;
Button btprev,btfb,btplay,btff,btnext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
mp = new MediaPlayer();
filepath = android.os.Environment.getExternalStorageDirectory().getPath();
file = new File(filepath,"MediaRecorderSample");
btplay=(Button) findViewById(R.id.btplay);
btff=(Button) findViewById(R.id.btff);
btnext=(Button) findViewById(R.id.btnxt);
btprev=(Button) findViewById(R.id.btprev);
btfb=(Button) findViewById(R.id.btfb);
btplay.setOnClickListener(this);
btff.setOnClickListener(this);
btnext.setOnClickListener(this);
btfb.setOnClickListener(this);
btprev.setOnClickListener(this);
sb= (SeekBar) findViewById(R.id.seekBar);
th = new Thread(){
#Override
public void run() {
int totalduration= mp.getDuration();
int currentposition=0;
sb.setMax(totalduration);
while(currentposition < totalduration)
{
try {
sleep(500);
currentposition = mp.getCurrentPosition();
sb.setProgress(currentposition);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//super.run();
}
};
// if(mp!=null)
// {
// mp.stop();
// mp.reset();
// mp.release();
// }
Intent i = getIntent();
Bundle b= i.getExtras();
pos = b.getInt("pos");
mysongs= b.getStringArrayList("mysongs");
Log.d("Mystring", String.valueOf(mysongs));
Log.d("path1",file.getAbsolutePath()+ "/" + mysongs.get(pos));
u = Uri.parse(file.getAbsolutePath()+ "/" + mysongs.get(pos)+".wav");
//mp.create(getApplicationContext(),u);
try {
if (mp != null) {
mp.stop();
}
mp.setDataSource(getApplicationContext(),u);
//mp.prepare();
mp.start();
th.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// mp = MediaPlayer.create(getApplicationContext(),u);
// try {
// mp.setDataSource(getApplicationContext(),u);
// mp.start();
// } catch (IOException e) {
// e.printStackTrace();
// }
//mp.start();
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id)
{
case R.id.btplay:
if(mp.isPlaying())
{
btplay.setText(">");
mp.pause();
}
else {
btplay.setText("||");
mp.start();
}
break;
case R.id.btff:
mp.seekTo(mp.getCurrentPosition()+ 5000);
break;
case R.id.btfb:
mp.seekTo(mp.getCurrentPosition()-5000);
break;
case R.id.btnxt:
mp.stop();
mp.reset();
mp.release();
pos =(pos+1)%mysongs.size();
u = Uri.parse(file.getAbsolutePath()+ "/"+mysongs.get(pos).toString());
// mp = MediaPlayer.create(getApplicationContext(),u);
try {
mp.setDataSource(getApplicationContext(),u);
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.btprev:
mp.stop();
mp.reset();
mp.release();
pos =(pos-1<0)? mysongs.size()-1: pos-1;
u= Uri.parse(file.getAbsolutePath()+ "/"+mysongs.get(pos).toString());
// mp = MediaPlayer.create(getApplicationContext(),u);
try {
mp.setDataSource(getApplicationContext(),u);
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
`

Media Recorder record application audio

I have an application that has a few buttons that have sounds (soundPool) I need to write them down on a flash card I make it through the MediaRecorder but when I run the app and then turn on the record playing and click stop recording application crashes you do not tell me what the problem is?
I expect that in the method recordStop
public class MainActivity extends Activity {
int kickSound;
SoundPool mSoundPool;
AssetManager assets;
private MediaRecorder mediaRecorder;
private MediaPlayer mediaPlayer;
private String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
assets = getAssets();
kickSound = loadSound("snare_trap.ogg");
ImageButton kick = (ImageButton)this.findViewById(R.id.imageButton1);
kick.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
playSound(kickSound);
}
return false;
}
});
fileName = Environment.getExternalStorageDirectory() + "/record.3gpp";
}
protected void playSound(int sound) {
if (sound > 0)
mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
private int loadSound(String fileName) {
AssetFileDescriptor afd = null;
try {
afd = assets.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Couldn't load file '" + fileName + "'", Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
}
public void recordStart(View v) {
try {
releaseRecorder();
File outFile = new File(fileName);
if (outFile.exists()) {
outFile.delete();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(AudioManager.STREAM_MUSIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(fileName);
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void recordStop(View v) {
mediaRecorder.stop();
}
public void playStart(View v) {
try {
releasePlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fileName);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void playStop(View v) {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
}
private void releaseRecorder() {
if (mediaRecorder != null) {
mediaRecorder.release();
mediaRecorder = null;
}
}
private void releasePlayer() {
mediaPlayer.release();
mediaPlayer = null;
}
#Override
protected void onDestroy() {
super.onDestroy();
releasePlayer();
releaseRecorder();
}
}
Why are you releasing the recorder to start out with? Releasing should only be used if you don't want to access the recorder anymore. Try moving the release to the end.

Android: Stop sound files playing at once

In the application I am currently writing, a user is able to select an entry from the database and play the contents of that entry: an entry is made up of a number of sound files (without a limit). In my application, I return the URI locations of the sound files of an entry (which have been stored in my database) in a List. The code is as follows:
public void audioPlayer() {
// set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
DatabaseHandler db = new DatabaseHandler(this);
Entry retrieveEntry = new Entry();
retrieveEntry = db.getEntry();
List<String> path = retrieveEntry.getAudioUri();
path.size();
System.out.println("PATH SIZE: " +path.size());
System.out.println("FILEZ: " + path);
Iterator<String> i = path.iterator();
String myAudio;
int count = 0;
while (i.hasNext()) {
System.out.println(count);
myAudio = i.next();
System.out.println("MY AUDIO: " + myAudio);
MediaPlayer player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
player.stop();
player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
count++;
}
}
My users require that there be user input for playing a file - is there a way to play the first file, then wait for the user to press the button, then play the second file, then wait for the user to press the button, etc.? At the moment, when the play button is pressed, all of the sound files that have been returned get played at the same time, rather than one after the other.
Thanks in advance for any help provided!
You can use this class to play a playlist. This will start one audio, when that audio finishes, it will start playing next audio till the end of the list. If you want to play the playlist in looping i.e start first audio after reaching end, then pass isLooping=true in startPlayingPlaylist(list,looping)
AudioPlayer player = new AudioPlayer();
player.startPlayingPlaylist(list, false);
Class
public class AudioPlayer{
MediaPlayer player = null;
ArrayList<String> playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list, boolean looping){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.setLooping(looping);
player.start();
// Set onCompletion listener
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(player.isLooping()==false){
player.release();
player = null;
}
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
Edit:
The class below receives a list of audios, then plays first Audio. It plays next audio when user calls startNextAudio() You can use any one of these according to your requirements
public class AudioPlayer{
MediaPlayer player = null;
ArrayList playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.start();
// Set onCompletion listener
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void startNextAudio(){
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
Log.i("AudioPlayer","Playlist reached at the end");
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
One approach would be to implement the MediaPlayer.OnCompletionListener interface. This gives you the MediaPlayer.onCompletion() callback method which you could use like so:
#Override
public void onCompletion(MediaPlayer mp) {
if (i.hasNext) {
// ...hand mp the next file
// ...show the user the 'play next' button
}
}
Note you also will need to call the MediaPlayer.setOnCompletionListener() method in your setup.

Setting an array of songs using MediaPlayer

I have 5 songs which i need to play one after the other, and it must loop from the first song after finishing the 5th song.
How do I use the MediaPlayer to achieve this?
public class MediaPlayerExample extends Activity implements MediaPlayer.OnCompletionListener {
int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
songs= new int[] {R.raw.song1,R.raw.song2,R.raw.song3,R.raw.song4};
mediaPlayer = MediaPlayer.create(this, songs[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
play();
}
private void play()
{
current_index = (current_index +1)% 4;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IllegalStateException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IOException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
}
}
Simple:
int[] songs = new int[]{R.raw.ab_hai_hamari_bari, R.raw.ab_khel_jamay_ga, R.raw.ab_khel_ke_dikha_psl_official_song, R.raw.chakka_choka_islamabad_united, R.raw.dil_dil_pakistan_junaid, R.raw.duniya_se_aagay, R.raw.hai_jazba_junoon_tho_himmat_na_haar, R.raw.hum_hain_pakistani_junaid, R.raw.jeet_ki_lagan, R.raw.jeetay_ga_pakistan_dedicate, R.raw.josh_e_junoon_pakistan_cricket, R.raw.karachi_kings_official, R.raw.lahore_qalandar_official, R.raw.multan_sultan_official, R.raw.peshawar_zalmi, R.raw.quetta_gladiator, R.raw.stand_up_for_the_champions};
you need to use CountDownTimer for this. CountDown timer has give you facility to do this one by one ::
MediaPlayer mp_xmPlayer2 = new MediaPlayer();
mp_xmPlayer2 = MediaPlayer.create(this, R.raw.bg_music_wav);
for(int i=0;i<5;i++)
{
CountDownTimer cntr_aCounter = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
mp_xmPlayer2.start();
}
public void onFinish() {
//change music name
}
};
cntr_aCounter.start();
}

Categories

Resources