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.
Related
I have hundreds of buttons, all with the same listener and action, but different names. Here is one with the name goes1:
public void goes1(){
final MediaPlayer mp = MediaPlayer.create(this, R.raw.goes1);
play_text_view = (TextView) this.findViewById(R.id.goes1);
play_text_view.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
lireXML("goes1");
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
}
I would like to have only one method where the name of the button would be passed to the method as a parameter. Something like this, with the String parameter mot:
public void playMot(String mot){
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mot);
play_text_view = (TextView) this.findViewById(R.id.mot);
play_text_view.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
lireXML(mot);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
}
but R.raw.mot and R.id.mot don't like this!
Should I really have hundreds of buttons, or is there a way around my problem?
Thanks
You are looking for Resources.getIdentifier. It looks up a resource id from a string name and type.
public void playMot(String mot) {
Resources res = getResources();
// Should error check this, returns 0 on error.
final rawId = res.getIdentifier(mot, "raw", getPackageName());
final MediaPlayer mp = MediaPlayer.create(this, rawId);
// Should error check this, returns 0 on error.
final resId = res.getIdentifier(mot, "id", getPackageName());
play_text_view = (TextView) this.findViewById(resId);
...
You can story the relation between name and raw id,the relation between name and view id,in hashMap,like this:
HashMap<String, Long> nameToRawId = new HashMap<String, Long>();
HashMap<String, Long> nameToViewId = new HashMap<String, Long>();
then get id from that hashMap int method playMot(String mot):
public void playMot(String mot){
final MediaPlayer mp = MediaPlayer.create(this, nameToRawId.get(mot));
play_text_view = (TextView) this.findViewById(nameToViewId.get(mot));
play_text_view.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
lireXML(mot);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
}
hope this can help you.
I have listview which contains a list of audio files with play button and seekbar. I displayed the listview using base adapter.
When I click a play button of a listview I want to play an audio file. I successfully implemented this but when i click another play button in list two audio files are playing continuously, It will continue for all onclick of play button. How can I restrict the mediaplayer to play in one position and if I click a another icon it have to stop the old media player and start to play the new one. Can anyone say me how do I implement this ?
Hi I am using this code
public class PlayerList extends Activity {
private static final String TAG = "log";
ListView listV;
ArrayList<HashMap<String, String>> arrList = new ArrayList<HashMap<String,String>>();;
String[] strArray = { "/mnt/sdcard/Nal.mp3", "/mnt/sdcard/Nal2.mp3",
"/mnt/sdcard/Nal3.mp3", "/mnt/sdcard/sample1.mp3", };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
listV = (ListView) findViewById(R.id.HomePagelistView1);
for (int i = 0; i < strArray.length; i++) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("title", "File Name");
hmap.put("description", "File description");
hmap.put("url", strArray[i]);
arrList.add(hmap);
}
FileListAdapter sAdapter = new FileListAdapter(arrList, PlayerList.this);
listV.setAdapter(sAdapter);
}
}
And the FileListAdapter file is given below
public class FileListAdapter extends BaseAdapter implements
OnCompletionListener, OnSeekBarChangeListener {
private MediaPlayer mp;
private Handler mHandler = new Handler();;
private Utilities utils;
SeekBar seekBar;// = (SeekBar) findViewById(R.id.homeList_seekBar1);
String songPath = "";
// ImageView imageVPlay;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater = null;
public FileListAdapter(ArrayList<HashMap<String, String>> data,
Context context) {
this.data = data;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.homelist, parent, false);
final ImageView imageVDownload = (ImageView) vi
.findViewById(R.id.homeListimageDownload); // download
final ImageView imageVPlay = (ImageView) vi
.findViewById(R.id.homeListimagePlay); // play
final TextView textVTitle = (TextView) vi
.findViewById(R.id.homeListTextTitle); // email ID
final TextView textVDescription = (TextView) vi
.findViewById(R.id.homeListTextDesc); // email ID
seekBar = (SeekBar) vi.findViewById(R.id.homeList_seekBar1);
textVTitle.setText(data.get(position).get("title"));
textVDescription.setText(data.get(position).get("description"));
// /////////////////////////////////// set image tick and download
String loadFilePath = data.get(position).get("url");
// String loadFileName = data.get(position).get("title");
File ffPath = new File(loadFilePath);
String loadfileNameWithExt = ffPath.getName();
Log.i(TAG, "load file and name path " + " " + loadfileNameWithExt
+ " " + loadFilePath);
imageVPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String selectFilePath = data.get(position).get("url");
String selectFileName = data.get(position).get("title");
Log.i(TAG, "selected file and name path " + selectFileName
+ " " + selectFilePath);
songPath = selectFilePath;
mediaplayerMethod(selectFilePath);
imageVPlay.setImageResource(R.drawable.list_pause);
textVTitle.setVisibility(View.INVISIBLE);
textVDescription.setVisibility(View.INVISIBLE);
seekBar.setVisibility(View.VISIBLE);
}
});
return vi;
}
protected void mediaplayerMethod(String filepath) {
Log.d(TAG, "mediaplayerMethod audio file path " + filepath);
mp = new MediaPlayer();
mp.setOnCompletionListener(FileListAdapter.this); // Important
seekBar.setOnSeekBarChangeListener(FileListAdapter.this);
utils = new Utilities();
playSong(filepath);
}
private void playSong(final String fileptath) {
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
String xmlString = (String) message.obj;
Log.d(TAG, "handleMessage ");
try {
// mp.prepare();
mp.start();
seekBar.setProgress(0);
seekBar.setMax(100);
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread() {
#Override
public void run() {
Log.d(TAG, "run ");
try {
mp.reset();
mp.setDataSource(fileptath);
Log.i(TAG, "internal file");
mp.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message message = handler.obtainMessage(1, "");
handler.sendMessage(message);
}
};
thread.start();
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
try {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
int progress = (int) (utils.getProgressPercentage(
currentDuration, totalDuration));
seekBar.setProgress(progress);
try {
double progVal = (progress / 100.0) * (360.0);
int progInt = (int) Math.ceil(progVal);
} catch (NumberFormatException e) {
Log.e(TAG, "NumberFormatException " + e);
}
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
} catch (IllegalStateException e) {
Log.e(TAG, "IllegalStateException " + e);
}
}
};
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.release();
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
updateProgressBar();
}
}// FileListAdapter
Release your old MediaPlayer when You going to start a new instance. For example:
protected void mediaplayerMethod(String filepath) {
Log.d(TAG, "mediaplayerMethod audio file path " + filepath);
if(mp != null){
mp.release();
}
mp = null;
mp = new MediaPlayer();
mp.setOnCompletionListener(FileListAdapter.this); // Important
seekBar.setOnSeekBarChangeListener(FileListAdapter.this);
utils = new Utilities();
playSong(filepath);
}
My app displays video and images interchangeably. When images are displayed music is played in the background and when video is played the music should stop playing. The problem is the music sometimes does not stop playing even though I am calling stop() function of the media player. Any help is appreciated thanks in advance. The code is as follows -
public class Standee implements Runnable, OnCompletionListener {
private Vector<File> files;
private Vector<String> timings;
private Handler h;
private VideoView video;
private ImageView image;
private Context ctx;
private int i;
private MediaPlayer player;
public MediaPlayer getMediaPlayer() {
return player;
}
public Standee(Context ctx, VideoView video, ImageView image) {
this.video = video;
this.image = image;
this.ctx = ctx;
i = 0;
h = new Handler();
files = new Vector<File>();
timings = new Vector<String>();
player = MediaPlayer.create(ctx, R.raw.background);
try {
FileReader fr = new FileReader(ConfigLoader.BETA_PATH + "media.tmr");
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
String[] data = s.split(";");
files.add(new File(ConfigLoader.BETA_PATH + data[0]));
timings.add(data[1]);
}
br.close();
video.setOnCompletionListener(this);
video.setMediaController(null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
h.removeCallbacks(this);
i++;
if (i >= files.size())
i = 0;
run();
}
#Override
public void run() {
if (files.elementAt(i).getAbsolutePath().endsWith(".jpg")) {
video.setVisibility(View.INVISIBLE);
image.setVisibility(View.VISIBLE);
if (video.isPlaying()) {
video.stopPlayback();
}
image.bringToFront();
player = MediaPlayer.create(ctx, R.raw.background);
try {
player.setLooping(true);
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
player.start();
showPhoto();
} else if (files.elementAt(i).getAbsolutePath().endsWith(".mp4")) {
if (player.isPlaying()) {
player.stop();
}
image.setVisibility(View.INVISIBLE);
video.setVisibility(View.VISIBLE);
video.bringToFront();
playVideo();
}
h.postDelayed(this, Integer.parseInt(timings.elementAt(i)));
i++;
if (i >= files.size())
i = 0;
}
public void start() {
h.post(this);
}
public void playVideo() {
Uri uri = Uri.parse(files.get(i).getAbsolutePath());
video.setVideoURI(uri);
video.requestFocus();
video.start();
}
public void showPhoto() {
image.setImageBitmap(BitmapFactory.decodeFile(files.elementAt(i)
.getAbsolutePath()));
}
// private void fadeout(Object obj){
// ValueAnimator videoAnim=ObjectAnimator.ofFloat(obj, "alpha", 1, 0);
// videoAnim.setDuration(3000);
// videoAnim.start();
// }
//
// private void fadein(Object obj){
// ValueAnimator imageAnim=ObjectAnimator.ofFloat(obj, "alpha", 0, 1);
// imageAnim.setDuration(3000);
// imageAnim.start();
// }
}
I have a problem when playing an mp3 in android, is something like a delay or a lag, ex:
if I have to reproduce the following: "Hello, how are you?", it only plays "how are you?" or says very low the "hello".
It happens in a ViewSonic V220 its a 22" tablet, in most of other devices, it works fine, but is in that one that seems to fail.
Its weird, becouse other apps(like youtube or media player) works fine.
This is my code, maybe i am doing something wrong:
public class SoundManager implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
private Parent mParent;
private MediaPlayer mediaPlayer;
String[] mp3_array;
int counter = 0;
public SoundManager(Parent parent) {
mParent = parent;
}
public void playSound(String[] url) throws IllegalArgumentException,
IllegalStateException, IOException {
mp3_array = url;
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (mediaPlayer.isPlaying()) {
mediaPlayer.reset();
}
mediaPlayer.setDataSource(url[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepareAsync();
}
public void stopMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
mp3_array = null;
counter = 0;
}
}
#Override
public void onCompletion(MediaPlayer mp) {
try {
Integer c = counter;
if (mp3_array != null && counter + 1 < mp3_array.length) {
mp.reset();
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
counter += 1;
mp.setDataSource(mp3_array[counter]);
mediaPlayer.prepareAsync();
} else {
if (mParent != null)
mParent.invokeJs("playSoundEnded()");
mp.release();
mp = null;
mp3_array = null;
counter = 0;
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
if (mParent != null)
mParent.invokeJs("playSoundStarted()");
mp.start();
}
}
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()