Search code examples
androidandroid-mediaplayer

How to populate listview and play audio file


I'am trying to populate listview from audio files and want to play the clicked item. It's not working. Any help.

MainActivity.java

public class MainActivity extends ListActivity {

public static File file; 
private List<String> filelist;
ArrayList<String> MyFiles = new ArrayList<String>();
MediaPlayer mp=new MediaPlayer();

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.list_item);
    final ListView musiclist = (ListView) findViewById(R.id.PhoneMusicList);

    MyFiles = new ArrayList<String>();  


        final String targetPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        file = new File( targetPath + "/AudioRecorder" ) ;
        File list[] = file.listFiles();

        // Binding resources Array to ListAdapter
         for( int i=0; i< list.length; i++)
            {
             MyFiles.add( list[i].getName() );
            }

        ListAdapter adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, MyFiles);

         musiclist.setAdapter(adapter);

musiclist.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
        //checking the position of item in list
        Object listItem =     musiclist.getItemAtPosition(position);
        Toast.makeText(MainActivity.this, ""+ musiclist, Toast.LENGTH_SHORT).show();


                playSong(targetPath + MyFiles.get(position));
    }
});
}

    private void playSong(String songPath) {
        // TODO Auto-generated method stub
         try {
                mp.reset();
                mp.setDataSource(songPath);
                mp.prepare();
                mp.start();

            } catch (IOException e) {
                Log.v(getString(R.string.app_name), e.getMessage());
            }
        }
    }

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <ListView
        android:id="@+id/PhoneMusicList" 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

This is my latest layout file:

<?xml version="1.0" encoding="utf-8"?>

  <ListView
      android:id="@+id/PhoneMusicList"
      android:layout_width="223dp"
      android:layout_height="334dp" />

  <ImageView
        android:id="@+id/play_pause"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:src="@drawable/pause"/>


I have created an already functioning app which displays ListView items and when an item in the list is selected, it then opens new activity. Inside the new_activity I have TextView and Image button displaying the audio buttons which is play, pause, & stop. the TextView functions perfectly but the image buttons refused to play audio file from raw folder. I have many audio files in the raw folder and want to assign each to each ListView that will open each new activity. Please help me edit this ListViewAdapter code below to play, pause, & stop playing each audio file.

How do I edit this NewActivity.java to populate it with songs from raw folder? I will highly appreciate your support thanks.

public class NewActivity extends AppCompatActivity {
    private String TAG = "NewActivity ----- ; " ;
    // Store instance variables
    private String title;
    private int page;
    MediaPlayer player;

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

        ActionBar actionBar = getSupportActionBar();
        TextView mDetailTv = findViewById(R.id.textView);


        //get data from previous activity when item of activity is clicked using intent
        Intent intent = getIntent();
        String mActionBarTitle = intent.getStringExtra("actionBarTitle");
        String mContent = intent.getStringExtra("contentTv");

        //setctionBar Title
        actionBar.setTitle(mActionBarTitle);
        //get text in text textView
        mDetailTv.setText(mContent);

        //ok we are done,




    public void  play(View v) {
        if (player == null) {
            player = MediaPlayer.create(this, R.raw.song_1);
            Toast.makeText(this, "Tune Playing", Toast.LENGTH_SHORT ).show();
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlayer();
                }
            });
        }
        player.start();
    }
    public void pause(View v) {
        if (player != null) {
            player.pause();
            Toast.makeText(this, "Tune Paused", Toast.LENGTH_SHORT ).show();
        }
    }
    public void stop(View v) {
    stopPlayer();
    }
    private void stopPlayer() {
        if (player != null) {
            player.release();
            player = null;
            Toast.makeText(this, "Tune Stoped", Toast.LENGTH_SHORT ).show();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopPlayer();
    }

}


Solution

  • Try with following code.

    public class Recording_List extends Activity{
    
        ListView mListView;
        ImageView mPlayPause;
    
        private File file;
        private MediaPlayer mp = new MediaPlayer();
        private Handler mHandler = new Handler();
        private List<String> myList = new ArrayList<String>();
    
        private static final String MEDIA_PATH = new String(
                Environment.getExternalStorageDirectory() + "/AudioRecorder/");
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.recordlist);
    
            mListView = (ListView) findViewById(R.id.recordList);
            mPlayPause = (ImageView) findViewById(R.id.play_pause);
    
            file = new File(MEDIA_PATH);
            if (!file.exists()) {
                file.mkdir();
            }
            File list[] = file.listFiles();
            for (int i = 0; i < list.length; i++) {
                myList.add(list[i].getName());
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, myList);
            adapter.notifyDataSetChanged();
            mListView.setAdapter(adapter);
            mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            mListView.setCacheColorHint(Color.TRANSPARENT);
    
            mListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    playSong(MEDIA_PATH + myList.get(position));
                }
            });
    
            mPlayPause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if (mp.isPlaying()) {
                        if (mp != null) {
                            mp.pause();
                            mPlayPause.setImageResource(R.drawable.play);
                        }
                    } else {
                        if (mp != null) {
                            mp.start();
                            mPlayPause.setImageResource(R.drawable.pause);
                        }
                    }
                }
            });
        }
    
        private void playSong(String songPath) {
            try {
                mp.reset();
                mp.setDataSource(songPath);
                mp.prepare();
                mp.start();
            } catch (IOException e) {
                Log.v(getString(R.string.app_name), e.getMessage());
            }
        }
    
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            mp.release();
        }
    }