简体   繁体   中英

How do i get the audio to play in a ListView in android Studio?

When it open in the emulator and i click on it the audio doesn't play. I've tried on several computers. I add a toast and the toast showed but audio didn't work. The mediaPlayer is declared already.

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, socialArrayPhrases);
    socialPhrases.setAdapter(arrayAdapter);

    socialPhrases.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position_of_phrase, long ld) {
            Toast.makeText(getApplicationContext(), socialArrayPhrases.get(position_of_phrase), Toast.LENGTH_SHORT).show();
            if (position_of_phrase == 0) {
                mediaPlayer = MediaPlayer.create(SpanishSocialPhrases.this, R.raw.audio);
            }

        }
    });
}

To play the sound from [MediaPlayer] , you need the following code :

mediaPlayer.start();

Your modified code :

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, socialArrayPhrases);
        socialPhrases.setAdapter(arrayAdapter);

        socialPhrases.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position_of_phrase, long ld) {
                    Toast.makeText(getApplicationContext(), socialArrayPhrases.get(position_of_phrase), Toast.LENGTH_SHORT).show();
                    if (position_of_phrase == 0) {
                        mediaPlayer = MediaPlayer.create(SpanishSocialPhrases.this, R.raw.audio);
                        mediaPlayer.setLooping(false); // Loop
                        mediaPlayer.start(); // Play Sound !
                    }

                }
            });
    }   

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