I have created a ListView and an each ListView item has 2 TextViews, an image and an audio file. Everything works fine and the audio files are played, but when I click on items several times and scroll up and down, the audio file is not played. What is wrong at that part?
Here is my java code :
public class NumbersActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers);
ArrayList<Word> words = new ArrayList<>();
words.add(new Word("one","un",R.drawable.number_one,R.raw.one));
words.add(new Word("two","deux",R.drawable.number_two,R.raw.two));
.......
ListView listView = (ListView) findViewById(R.id.numberViewlist);
WordAdapter itemsAdapter = new WordAdapter(this,
words,R.color.category_numbers,listView);
listView.setAdapter(itemsAdapter);
}
}
and this is the code for the WordAdaper :
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MediaPlayer mp = MediaPlayer.create(getContext(),currentWord.getsound());
mp.start();
}
});
Use this code:
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
mp = null;
}
Please refer this Doc !
Related
I got a problem with playing two MediaPlayers simultaneously.
In my code I made a spinner to let the user to choose his first song and then the second song, at the moment that the user chooses the first song it starts to play and when the user choose the second song it will play with the first one.
But the problem is that, when the user chse the second song it stops the first one...
What can I do to fix it?
Ty!
The code:
public void setSpinner() {
Spinner spine = (Spinner) findViewById(R.id.spinner3);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.song, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spine.setAdapter(adapter);
final MediaPlayer mp1 = new MediaPlayer();
spine.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String st = parent.getItemAtPosition(position).toString();
if (st.equals("First Song")) {
setMedia1(mp1);
mp1.start();
}
if (st.equals("Second Song")) {
setMedia2(mp1);
mp1.start();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void setMedia1(MediaPlayer mp2) {
Bundle b1=getIntent().getExtras();
float s = b1.getFloat("speed");
Bundle b2=getIntent().getExtras();
float v = b2.getFloat("volume");
try {
String s1 = getIntent().getStringExtra("song1");
final Uri uri1 = Uri.parse(s1);
mp2.setDataSource(getApplicationContext(), uri1);
mp2.prepare();
mp2.setVolume(v,v);
mp2.setPlaybackParams(mp2.getPlaybackParams().setSpeed(s));
} catch (Exception e) {
}
}
public void setMedia2(MediaPlayer mp2) {
Bundle b3 = getIntent().getExtras();
float sp1 = b3.getFloat("speed1");
Bundle b4 = getIntent().getExtras();
float vo1 = b4.getFloat("volume1");
try {
String s2 = getIntent().getStringExtra("song3");
final Uri uri2 = Uri.parse(s2);
mp2.setDataSource(getApplicationContext(), uri2);
mp2.prepare();
mp2.setVolume(vo1, vo1);
mp2.setPlaybackParams(mp2.getPlaybackParams().setSpeed(sp1));
} catch (Exception e) {
}
}
try SoundPool,its a better method of dealing with multiple audio files at the same time.
Heres the documentation:
http://developer.android.com/reference/android/media/SoundPool.html
Heres the example:
http://examples.javacodegeeks.com/android/android-soundpool-example
Hope this helps
Reference
Try using two MediaPlayer instances. Change your setSpinner method to do something like:
public void setSpinner() {
Spinner spine = (Spinner)findViewById(R.id.spinner3);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.song, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spine.setAdapter(adapter);
// You were only creating a single MediaPlayer instance in your version...
final MediaPlayer mpA = new MediaPlayer();
final MediaPlayer mpB = new MediaPlayer();
spine.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String st = parent.getItemAtPosition(position).toString();
if (st.equals("First Song")) {
// Use mpA for the first song
setMedia1(mpA);
mpA.start();
}
else if (st.equals("Second Song")) {
// Use mpB for the second song
setMedia2(mpB);
mpB.start();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
I do not know if that will get the exact behavior you are looking for, but it stands a better chance at playing two songs simultaneously than using a single MediaPlayer instance.
Here is a quick show of the issue with my current code. It is created in Android Studio:
public class OptionActivity extends Activity {
Spinner spnr;
int songs[] = new int[] {R.raw.sound1,R.raw.sound1,R.raw.sound3,R.raw.sound4};
MediaPlayer myMediaPlayer;
int current_index = 0;
String[] mySelectSounds = {
"Robot",
"Manly man",
"Woman",
"Cat",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option);
myMediaPlayer = MediaPlayer.create(this, songs[0]);
spnr = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, mySelectSounds);
spnr.setAdapter(adapter);
spnr.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int position = spnr.getSelectedItemPosition();
Toast.makeText(getApplicationContext(), "You have selected " + mySelectSounds[+position], Toast.LENGTH_LONG).show();
current_index = (current_index + position);
if (position == 3) {
myMediaPlayer.start();
//What to put here, to make it change the array number in myMediaPlayer = MediaPlayer.create(this, songs[0]);?
}}
I have 4 arrays, which are supposed to be sounds. I want to be able to change which sound is used in the different positions of the dropdown menu/spinner through an array.
My issue is, when I create the myMediaPlayer in the OnCreate, I don't know how to change it. The int current_index is set to be the same as the position of the spinner, so I want to add that to the array's position, according to the menu number in my spinner. I have tried my own hand with it, but I'm fairly inexperienced with android studio, and the sample I have found, used the code
if (position == 3) {
getResources().openRawResourceFd(songs[current_index]);
myMediaPlayer.start();
}
which, according to the other questions asked here seems to work, but it is not working for me.
You need to create a new MediaPlayer like this in your item click
MediaPlayer mp = MediaPlayer.create(OptionActivity.this, songs[current_index]);
Try
current_index = position;
if (current_index == 3) {
myMediaPlayer.start();
myMediaPlayer = MediaPlayer.create(this, songs[current_index]);
}}
I have a listview of all musics in the phone. Whenever user click on the item of the listview it starts a same activity of my player class every time. The first music chosen by user plays great. But the problem is when user choose the second music, it starts play new one without stopping previous one. So the result is two musics playing together.
This is my listview onItemClickListener()
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) view;
String songId = tv.getText().toString();
Intent i = new Intent(getActivity(), player.class);
i.putExtra("id", songId);
startActivity(i);
}
});
and the main portion of my player class:
private MediaPlayer mp;
Bundle extras = getIntent().getExtras();
String songId = null;
if(extras != null){
songId = extras.getString("id");
play.setBackgroundResource(R.drawable.pause);
}
find(songId);
private void find(String songName) {
for(int t = 0; t < songs.size(); t++){
if(("" + songs.get(t)).endsWith(songName)){ //songs, an ArrayList of music files path
Uri myUri = Uri.parse("" + songs.get(t));
stopPlaying();
mp = MediaPlayer.create(this, myUri);
mp.start();
break;
}
}
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
I have tried a several way to get rid of this problem. But I din't understand what I am missing. I can provide full code if needed.
Since you have called stopPlaying method, ideally it should stop. Try adding this line of code
mp.setLooping(false); before mp.start();
Not sure if this would fix the issue.
Also Try this
if(mp!=null && mp.isPlaying())
instead of
if (mp != null)
in addition to previous answer
Define your media player as static
static MediaPlayer mp;
In my activity i have two spinners, one image view and two buttons.
depending on first spinner the second spinners should change. and while selecting birds in first spinner the second spinner should show parrot peacock etc. while selecting parrot in second spinner i should get the image of parrot.
till this i am getting.
but now what i want is while i press a button then i should get the voice of parrot.
in this code when i am pressing the button i am getting the same voice for every picture change in second spinner
public class MainActivity extends Activity {
ImageView displayIV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
;
Button b1;
b1=(Button)findViewById(R.id.button1);
Spinner friend = (Spinner) findViewById(R.id.spinner1);
final Spinner subFriend = (Spinner) findViewById(R.id.spinner2);
displayIV=(ImageView)findViewById(R.id.imageView1);
final ArrayList<String> friend_options = new ArrayList<String>();
final ArrayList<String> subfriend_options = new ArrayList<String>();
friend_options.add("Nuz");
friend_options.add("Dur");
friend_options.add("Tara");
friend_options.add("Sama");
ArrayAdapter<String> friendAdapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
friend_options);
friend.setAdapter(friendAdapter);
ArrayAdapter<String> subFriendAdapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_spinner_item,subfriend_options);
subFriend.setAdapter(subFriendAdapter);
friend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
String friendName =
friend_options.get(position).toString();
resetFriend(friendName);
// subFriend.setAdapter(null);
}
private void resetFriend(String friendName) {
subfriend_options.removeAll(subfriend_options);
if (friendName.equals("Nuz")) {
subfriend_options.add("Nuz_1");
subfriend_options.add("Nuz_2");
subfriend_options.add("Nuz_3");
subfriend_options.add("Nuz_4");
} else if (friendName.equals("Dur")) {
subfriend_options.add("Dur_1");
subfriend_options.add("Dur_2");
subfriend_options.add("Dur_3");
subfriend_options.add("Dur_4");
} else if (friendName.equals("Tara")) {
subfriend_options.add("Tara_1");
subfriend_options.add("Tara_2");
subfriend_options.add("Tara_3");
subfriend_options.add("Tara_4");
} else {
subfriend_options.add("Sama_1");
subfriend_options.add("Sama_2");
subfriend_options.add("Sama_3");
subfriend_options.add("Sama_4");
}
ArrayAdapter<String> subFriendAdapter = new
ArrayAdapter<String>( getApplicationContext(),
android.R.layout.simple_spinner_item,
subfriend_options);
subFriend.setAdapter(subFriendAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
subFriend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
arg0.getItemAtPosition(arg2);
final ImageView im =
(ImageView)findViewById(R.id.imageView1);
String s=((TextView)arg1).getText().toString();
if(s.equals("Tara_1")){
im.setImageDrawable(getResources().getDrawable(R.drawable.crow));
}
if(s.equals("Tara_2"))
im.setImageDrawable(getResources().getDrawable(R.drawable.india1));
if(s.equals("Tara_3"))
im.setImageDrawable(getResources().getDrawable(R.drawable.peacock));
if(s.equals("Tara_4"))
im.setImageDrawable(getResources().getDrawable(R.drawable.robin1));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//MediaPlayer mMediaPlayer = MediaPlayer.create(this,
R.raw.Kalimba);
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.abc);
mp.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
In the setOnClickListener method of your button, b1, you need to know which image has been selected on the spinner (your description is a little bit confusing so i don't have clear exactly which spinner is going to change the sound that you app has to reproduce).
Anyway, let think that the spinner is "friend_options".
In you setOnClickListener we have to know which item has been selected for the user when click on the button, right? And depending of which item was selected, we will play one specific sound.
So....
Another important poin is that you should create the variable of the mediaplayer outside of the onclickListener, like a class variable:
//Class variable:
public MediaPlayer mp;
In the onCreate method you should initialize the MediaPlayer component:
public void onCreate()
{
MediaPlayer.create(MainActivity.this, R.raw.abc); //Default sound, it is not
//importat because we are going
//to chain the value of the
//file to reproduce in the next
//step.
}
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Here we are going to take the item selected:
String itemSelected = spinner.getSelectedItem().toString();
int soundToPlayId=0;
if(itemSelected.equals("Nuz"))
{
soundToPlayId = R.raw.Kalimba ;
}
else if(itemSelected.equals("Dur"))
{
soundToPlayId = R.raw.abc;
}
// etc etc etc --> you should put all the sound associated to all the
// friends
//And now you only have to reproduce if the item was selected properly:
if(soundToPlayId !=0) //if the id is different to 0:
{
mp = MediaPlayer.setDataSource(MainActivity.this, soundToPlayId);
mp.start();
}
}
});
Let see if it is working!!! Ask me if you have any doubt...and if the answer is correct, vote me and check as correct!!! (I need points, thanks!)
Hey I want to create a layout like this for my application. Of course the functionalities will be differents. I'm studying the source code for this, and I found the xml files that does that. I just dont know how to implement that in the activity, how to call, what to create, a listview, etc.
I mean, I just want to list the name with a bigger font and the date like in the image, with a small font but aligned to the right.
Because, I want to get the data from the database I've created and print it like this list of CallLog.
I mean, how Android makes the date with that icon align in the right, with a small font size?
So this is my activity, I just dont know what xml file from the source code to use, or what method to implement so I can print the data like the image example.
public class RatedCalls extends ListActivity {
private static final String LOG_TAG = "RatedCalls";
private TableLayout table;
private CallDataHelper cdh;
private TableRow row;
private TableRow row2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recent_calls);
Log.i(LOG_TAG, "calling from onCreate()");
cdh = new CallDataHelper(this);
startService(new Intent(this, RatedCallsService.class));
Log.i(LOG_TAG, "Service called.");
Log.i(LOG_TAG, "before call fillList");
/*
* mAdapter = new RecentCallsAdapter();
* getListView().setOnCreateContextMenuListener(this);
* setListAdapter(mAdapter);
*/
fillList();
Log.i(LOG_TAG, "after call fillList");
}
public void onResume() {
super.onResume();
fillList();
}
public void fillList() {
Log.i(LOG_TAG, "entered on fillList");
List<String> ratedCalls = new ArrayList<String>();
ratedCalls = this.cdh.selectTopCalls();
//setListAdapter(new ArrayAdapter<String>(this, R.layout.recent_calls_list_item,
//ratedCalls));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
getListView().setOnCreateContextMenuListener(this);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_LONG).show();
}
});
}
}
Thanks.
It's just a 2 step process:
Create a Layout Xml file which represents 1 item of your list.
Extend Array Adapter and use your custom layout file there. There are several examples on the internet on how to extend Array Adapter.
I'm going to create a listview with multiple textviews.