简体   繁体   中英

How to play a specific sound for a Listview item when it is clicked

I am creating an android dictionary app with sounds... I have listview , when an item is selected, a new activity open, inside the new activity contains 4 textviews and an image button, the textviews function perfectly but the image button was not. The audio files are placed in raw folder. How can I put the specific sounds of an item that was clicked? Here's the code:

MainActivityJava

public class MainActivity extends AppCompatActivity {

ListView lv;
SearchView sv;


String[] tagalog= new String[] {"alaala (png.)","araw (png.)","baliw (png.)","basura (png.)",
        "kaibigan (png.)","kakatuwa (pu.)", "kasunduan (png.)","dambuhala (png.)",
        "dulo (png.)","gawin (pd.)","guni-guni (png.)","hagdan (png.)","hintay (pd.)",
        "idlip (png.)","maganda (pu.)","masarap (pu.)", "matalino (pu.)"};

int[] sounds= new int[]{R.raw.alaala,
                R.raw.araw,
                R.raw.baliw,
                R.raw.basura,
                R.raw.kaibigan,
                R.raw.kakatuwa,
                R.raw.kasunduan,
                };


ArrayAdapter<String> adapter;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    lv = (ListView) findViewById(R.id.listView1);
    sv = (SearchView) findViewById(R.id.searchView1);

    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tagalog);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String tagword =tagalog[position];

            String[] definition = getResources().getStringArray(R.array.definition);
            final String definitionlabel = definition[position];

            String[] cuyuno = getResources().getStringArray(R.array.cuyuno);
            final String cuyunodefinition = cuyuno[position];

            String[] english = getResources().getStringArray(R.array.english);
            final String englishdefinition = english[position];


            Intent intent = new Intent(getApplicationContext(), DefinitionActivity.class);
            intent.putExtra("tagword", tagword);
            intent.putExtra("definitionlabel", definitionlabel);
            intent.putExtra("cuyunodefinition",cuyunodefinition);
            intent.putExtra("englishdefinition", englishdefinition);



            startActivity(intent);

        }
    });


    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String text) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String text) {

            adapter.getFilter().filter(text);
            return false;
        }



    });

}

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}

}

DefinitionActivity.java

public class DefinitionActivity extends AppCompatActivity {

MediaPlayer mp;

String tagalogword;
String worddefinition;
String cuyunoword;
String englishword;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_definition);

    TextView wordtv = (TextView) findViewById(R.id.wordtv);
    TextView definitiontv = (TextView) findViewById(R.id.definitiontv);
    TextView cuyunotv = (TextView) findViewById(R.id.cuyunotv);
    TextView englishtv = (TextView) findViewById(R.id.englishtv);
    ImageButton playbtn = (ImageButton) findViewById(R.id.playbtn);


    final Bundle extras = getIntent().getExtras();

    if (extras != null) {

        tagalogword = extras.getString("tagword");
        wordtv.setText(tagalogword);

        worddefinition = extras.getString("definitionlabel");
        definitiontv.setText(worddefinition);

        cuyunoword = extras.getString("cuyunodefinition");
        cuyunotv.setText(cuyunoword);

        englishword = extras.getString("englishdefinition");
        englishtv.setText(englishword);

    }

    playbtn.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {

        }
    });


}

您可以在意向附加中传递原始id并在meadiaPlayer上播放

What you want to accomplish is pretty simple.

you can ofcourse pass the id.

But I created this method for your case you can paste it in your activity or class and make a call to it. In my case, I put this method in a class that holds all the common functions, methods, strings, etc. The choice is yours :

public static void playDisSound(Context c, int soundID){
                //Play short tune
                MediaPlayer mediaPlayer = MediaPlayer.create(c, soundID);
                mediaPlayer.setOnCompletionListener( new OnCompletionListener(){
                    @Override
                    public void onCompletion( MediaPlayer mp){
                        mp.release();
                    }
                });
                mediaPlayer.start();
            }

And this is how to use it in your case :

Example I want to play an audio track from :

int[] sounds= new int[]{R.raw.alaala,
                R.raw.araw,
                R.raw.baliw,
                R.raw.basura,
                R.raw.kaibigan,
                R.raw.kakatuwa,
                R.raw.kasunduan,
                };

So I just do :

//TODO ~ pls. remember to define context inside "onCreate" as 

//call this before "onCreate"
Context context;

//And do this inside "onCreate"   :
context = getApplicationContext();
OR
context = MainActivity.this;

//Then here comes the solution, just make a call to the playDisSound method with the id , in this case the "sounds[postion_referencer_i]"

playDisSound(context, sounds[postion_referencer_i]);

//And now on the question of what your "position_referencer_i" would be .... it also depends on how you intend to pass the id.

Are your going to make a match between the position picked and the position of the sound. It depends on you. But I would have created a set of integers to signify which try I want to play and do a matching simple calculation between the position picked for the item clicked to arrive at the position_referencer_id.

//But simply : note that in your array if I want to play for example "R.raw.baliw" I would just call :

playDisSound(context, R.raw.baliw);

I hope this works perfectly for you. So if I elaborated too much. Do let me know if you may need to stream the sound so I would just paste/send you a very cool method I have been using here in an app am working.

//FINALLY PLS. Remember this : this method would play the sound alright but it wont hesitate to play the sound all over again if you repeat the process. So do remember to check if the sound did play and finished before allowing the user to repeat, if not it could lead to repeated or kind of two speakers playing from the same song but at different time. (And the user may start to think that there is problem with the app. Pls. be very logical and sensitive in using this method)

In solving that, you can disable the button or the UI element that initiates the sound playing until the sound has finished playing, by way of monitoring duration of the track (which I am sure you should know and inculcate into your logic or by simply listening if sound is already playing)

All the best. Era. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM