My ProgressBar does not reset after audio is done. It reset after some audio's but not others not sure why. Also would like to make pause icon change to play when audio is done if anyone can help out with that to, that will be great!
Heres code:
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound01; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound02; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound03;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player1.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.pauseicon)
if(mp.isPlaying()){
mp.pause();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.playicon);
} else {
mp.start();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.pauseicon);
}}});
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
First issue:
In the thread "run" method, in the while condition you are saying:
(currentPosition<total)
this way "currentPosition" value will never reach "total" value and your progressbar won't go, you should use "less than or equal":
(currentPosition<=total)
so code will be:
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && mp.isPlaying() && currentPosition<=total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
Second issue:
You can change the ImageButton using "mp.setOnCompletionListener(this)" like this:
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
Set it while initializing the mediaplayer, before mp.start()
Related
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();
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;
}
}
}
`
I am trying to play audio and image concurrently in android...i have take one image-view and two buttons for go to back and go to next..when i click on next button and go on its working perfectly fine but as soon as i clicked on back button only audio file changes not the image. if i again clicked on back button then image changes but with another audio file..please help me out with this..thanks here is my code
public class Main extends Activity{
Button btn_back,btn_play,btn_next;
ImageView img_view;
int current_img = 0;
int current_aud = 0;
MediaPlayer mp;
int[] images = {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5,
R.drawable.img6,R.drawable.img7,R.drawable.img8,R.drawable.img9,R.drawable.img10,
R.drawable.img11,R.drawable.img12};
int[] audio = {R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,
R.raw.aud,R.raw.a,R.raw.aud,R.raw.a};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_back = (Button)findViewById(R.id.button1);
btn_play = (Button)findViewById(R.id.button2);
btn_next = (Button)findViewById(R.id.button3);
img_view = (ImageView)findViewById(R.id.imageView1);
img_view.setImageResource(R.drawable.ic_launcher);
mp =new MediaPlayer();
btn_play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
}
});
btn_next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
current_img = current_img % images.length;
img_view.setImageResource(images[current_img]);
current_img ++;
try {
if(mp != null){
if(mp.isPlaying()){
mp.stop();
// mp.release();
}
}
current_aud = current_aud % audio.length;
mp.reset();
mp = MediaPlayer.create(Main.this, audio[current_aud]);
mp.start();
current_aud ++;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
btn_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
current_img = (current_img + images.length) % images.length;
current_img --;
img_view.setImageResource(images[current_img]);
try {
if(mp != null){
if(mp.isPlaying()){
mp.stop();
// mp.reset();
}
}
current_aud = (current_aud + audio.length)% audio.length;
mp.reset();
mp = MediaPlayer.create(Main.this, audio[current_aud]);
current_aud --;
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
public class Main extends Activity implements OnClickListener{
Button btn_back,btn_play,btn_next;
ImageView img_view;
int current_img = 0;
int current_aud = 0;
MediaPlayer mp;
int[] images = {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5,
R.drawable.img6,R.drawable.img7,R.drawable.img8,R.drawable.img9,R.drawable.img10,
R.drawable.img11,R.drawable.img12};
int[] audio = {R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,R.raw.aud,R.raw.a,
R.raw.aud,R.raw.a,R.raw.aud,R.raw.a};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_back = (Button)findViewById(R.id.button1);
btn_play = (Button)findViewById(R.id.button2);
btn_next = (Button)findViewById(R.id.button3);
img_view = (ImageView)findViewById(R.id.imageView1);
img_view.setImageResource(R.drawable.ic_launcher);
mp =new MediaPlayer();
btn_play.setOnClickListener(this);
btn_next.setOnClickListener(this);
btn_back.setOnClickListener(this);
}
#Override
public void OnClick(View view){
switch(view.getId()){
case R.id.button1:
current_img --;
if(current_img == -1){
current_img = images.length-1;
}
img_view.setImageResource(images[current_img]);
if(mp != null && mp.isPlaying()){
mp.stop();
}
current_aud--;
if(current_aud == -1){
current_aud = audio.length-1;
}
mp.reset();
mp = MediaPlayer.create(Main.this, audio[current_aud]);
current_aud --;
mp.start();
break;
case R.id.button3:
current_img ++;
if(current_img == images.length){
current_img = 0;
}
img_view.setImageResource(images[current_img]);
if(mp != null && mp.isPlaying()){
mp.stop();
}
current_aud++;
if(current_aud == audio.length){
current_aud = 0;
}
mp.reset();
mp = MediaPlayer.create(Main.this, audio[current_aud]);
current_aud --;
mp.start();
break;
case R.id.button2:
if(mp != null && mp.isPlaying()){
mp.stop();
}
break;
}
}
}
You just have to change this for Next
if (currentimg < (media_list.size())) {
currentimg+= 1;
} else {
currentimg = 0;
}
and for back
if (currentimg > 0) {
currentimg -= 1;
} else {
currentimg = 0;
}
Just add it. It should work
I'm facing with a problem. I want to get duration of video when i 'm recording it.
I can get duration of video when it's finish by code
MediaPlayer mp = MediaPlayer.create(mContext, Uri.parse(video));
if(mp == null)
return -1;
int duration = mp.getDuration();
mp.release();
But i want to get duration everytime when i record video to update to progressbar.
Hope your reply!
private class PlaybackObserver extends Thread {
public void run() {
currentPosition = 0;
try {
while (!killObserverThread) {
Thread.sleep(1000);
currentPosition = (int) mediaPlayer.getCurrentPosition();
runOnUiThread(new Runnable() {
public void run() {
yourProgressBar.setProgress(currentPosition);
}
});
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
killObserverThread = false;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (task == null || !task.isAlive()) {
task = new PlaybackObserver();
task.start();
}
startPlaying();
}
add a private class for your UiThread to update your seekbar/progressbar. Then start it from onResume()
Hi guys i am having 3 audio files and three images with three text displaying for each image.
Now what i have done as soon as application starts the first image,text and audio file starts playing and after completion of that 2nd one starts similarly 3rd one starts.
Basically i need these to played sequentially one after the other but dynamically since i am having some 20 files similar to this
below is my code
public class S001Activity extends Activity {
/** Called when the activity is first created. */
ImageView img;
TextView display;
MediaPlayer apple = new MediaPlayer();
MediaPlayer boy = new MediaPlayer();
MediaPlayer cat = new MediaPlayer();
//Runnable rb,rc;
Document doc;
DocumentBuilder builder;
Handler handler = new Handler();
int i=0;
int noOfQues = 0;
//int media[] = {R.raw.apple_v,R.raw.boy_v,R.raw.cat_v};
//int image[] = {R.drawable.apple,R.drawable.boy,R.drawable.cat};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView)findViewById(R.id.img);
display = (TextView)findViewById(R.id.display);
img.setBackgroundResource(R.drawable.apple);
apple = MediaPlayer.create(this, R.raw.apple_v);
apple.start();
xml();
boy = MediaPlayer.create(this, R.raw.boy_v);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
i++;
img.setBackgroundResource(R.drawable.boy);
boy.start();
xml();
}
},apple.getDuration()+ 2000 );
cat = MediaPlayer.create(this, R.raw.cat_v);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
i++;
img.setBackgroundResource(R.drawable.cat);
cat.start();
xml();
}
},apple.getDuration()+ boy.getDuration()+ 2000 );
}
public void xml(){
try {
InputStream in = getResources().openRawResource(R.raw.topic1761);
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(in, null);
NodeList listOfPersons = doc.getElementsByTagName("Point");
noOfQues = listOfPersons.getLength();
System.out.println("items======= " + noOfQues);
Node firstPersonNode = listOfPersons.item(i);
Element firstPersonElement = (Element) firstPersonNode;
NodeList firstNameList = firstPersonElement.getElementsByTagName("PracticeText");
Element firstNameElement = (Element) firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
display.setText(((Node) textFNList.item(0)).getNodeValue().trim());
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
}
}
edited code
#Override
public void onCompletion(MediaPlayer mps) {
// TODO Auto-generated method stub
//MediaPlayer mps = new MediaPlayer();
img.setBackgroundResource(image[i]);
handler.post(new Runnable() {
#Override
public void run() {
xml();
AssetFileDescriptor afd = getResources().openRawResourceFd(media[i]);
mp.reset();
try {
mp.setDataSource(afd.getFileDescriptor());
afd.close();
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
You can use array or a list to store the list of music files, image files and text.
Then play the next one in MediaPlayer.OnCompletionListener.
EDIT:
int media[] = {R.raw.apple_v,R.raw.boy_v,R.raw.cat_v};
MediaPlayer mp = new MediaPlayer();
// in OnCompletionListener,
index = index + 1; //add proper checks
handler.post(new Runnable() {
#Override
public void run() {
AssetFileDescriptor afd = getResources().openRawResourceFd(media[index]);
mp.reset();
mp.setDataSource(afd.getFileDescriptor());
afd.close();
mp.prepare();
mp.start();
}
});
I think you can get the idea with the above sample code.