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.
Related
Here I'm trying to send my value that gets from a spinner (array adapter) to another activity. I populate my spinner using json and my spinner is something like below.
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, villageList);
spinner_village.setAdapter(adp);
spinner_village.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
try {
JSONObject villageObject = arrayList.get(position);
String villageId = villageObject.getString("id");
String villageName = villageObject.getString("name");
String villageCode = villageObject.getString("village_code");
Toast.makeText(Region.this, villageCode, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Now I'm trying to get "villageCode" to my on create a method so that I can pass this value to my another activity. What I've done so far is
spinner_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Region.this, Participant_Details.class)
.putExtra("catment_code", **-----**);
Region.this.startActivity(intent);
Region.this.finish();
}
})
putextra is giving error. How can I resolve it or what is the problem.
You can set the string villageCode as global variable (You can make your variable global by declaring it in the class level It should not be inside any method in your class) and then you extract the value of the string in your onClick method. Like so:
spinner_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Region.this, Participant_Details.class)
.putExtra("catment_code", villageCode); //the value is being set here
Region.this.startActivity(intent);
Region.this.finish();
}
})
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 !
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]);
}}
Why does onItemSelected not fire straight after setSelection on transportMode but only after the populateEditData method has finished?
I need onItemSelected to fire because I dynamically change the dataset for transport company in onItemSelected based on the value selected for transportMode
protected void onCreate(Bundle savedInstanceState)
{
transportMode = (Spinner) findViewById(R.id.spnrTransportMode);
transportModeAdapter = new CustomSpinnerAdapter(this, R.id.txtvTransporModeSpinner, R.layout.custom_spinner_row_item_mode, getResources().getStringArray(R.array.transport_mode_array), "mode");
transportMode.setAdapter(transportModeAdapter);
transportMode.setOnItemSelectedListener(this);
transportCompany = (Spinner) findViewById(R.id.spnrTransportCompany);
transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvTransportCompany, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_bus_companies_array), "company");
transportCompany.setAdapter(transportCompanyAdapter);
....
if(useActivityForEdit)
populateEditData();
}
public void populateEditData(int modeIndex, int companyIndex)
{
//Two spinners transportMode has onItemSelected listener
transportMode.setSelection(modeIndex);
//On item selected should trigger here then complete before setting transport company selection
transportCompany.setSelection(companyIndex);
}
public void onItemSelected(AdapterView<?> arg0, View view, int selectedIndex, long arg3)
{
//dynamically changes data of transportCompany adapter
if(transportMode.getSelectedItem().toString().equalsIgnoreCase("bus"))
{
transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvContent, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_bus_companies_array), "company");
transportCompany.setAdapter(transportCompanyAdapter);
transportCompany.setClickable(true);
}
else if(transportMode.getSelectedItem().toString().equalsIgnoreCase("train"))
{
transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvContent, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_train_companies_array), "company");
transportCompany.setAdapter(transportCompanyAdapter);
transportCompany.setClickable(true);
}
else if(transportMode.getSelectedItem().toString().equalsIgnoreCase("tram"))
{
transportCompanyAdapter = new CustomSpinnerAdapter(this, R.id.txtvContent, R.layout.custom_spinner_row_item_company, getResources().getStringArray(R.array.transport_tram_companies_array), "company");
transportCompany.setAdapter(transportCompanyAdapter);
transportCompany.setClickable(true);
}
}
Try adding transportCompany.setAdapter(transportCompanyAdapter); after transportCompany.setSelection(companyIndex);
and adding transportMode.setAdapter(transportModeAdapter); after transportMode.setSelection(modeIndex);
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!)