Welcome folks today in this blog post we will be seeing how to display and play audio
files from storage inside listview
widget using MediaPlayer
class in java. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new android
project inside the android studio and then you will see the below directory
structure as shown below at the end
of the project.
Now we need to edit the AndroidManifest.xml
file and add the necessary permissions
to read all the mp3
audio files from the system.
AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.Mp4toMp3Project" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
Editing the Main Layout
Now we need to edit the activity_main.xml
file for the project where we will be having the listView widget where we will be displaying the list
of mp3 files to be played.
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> |
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static final int REQUEST_PERMISSION_READ_EXTERNAL_STORAGE= 1 ; private ArrayList<String> audioFiles = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION_READ_EXTERNAL_STORAGE); } getSongs(); } // Get a reference to the device's external storage directory } public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSION_READ_EXTERNAL_STORAGE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted, you can now access files on external storage getSongs(); } else { // Permission denied, you cannot access files on external storage } } } private void getSongs(){ File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); //Log.d("t", String.valueOf(root)); // Find all audio files in the storage directory File[] files = root.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".mp3") || name.endsWith(".wav") || name.endsWith(".m4a"); } }); // Add the file paths to the ArrayList for (File file : files) { audioFiles.add(file.getAbsolutePath()); } // Set up ListView to display audio files ListView listView = findViewById(R.id.list_view); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, audioFiles); listView.setAdapter(adapter); // Set onItemClickListener to play selected audio file listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, AudioPlayer.class); intent.putExtra("audioFilePath", audioFiles.get(position)); startActivity(intent); } }); } } |
As you can see inside the java code we are first of all taking the runtime
permission of reading it from the external
storage from the user if the android device is above 10. And then we are loading all the mp3
or wav
files inside the listView
using the ArrayAdapter
class. And after that when we tap
on individual song or mp3
audio file. We are redirecting to the new activity
where we will be having two buttons to play
and stop
the song using the MediaPlayer
class.
And now we need to create the AudioPlayer.java
Activity where we need to copy paste the below java
code as shown below
AudioExtractor.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; public class AudioPlayer extends AppCompatActivity { private MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_audio_player); // Get audio file path from intent String audioFilePath = getIntent().getStringExtra("audioFilePath"); // Create MediaPlayer and set audio file path mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(audioFilePath); mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } // Set up play button to play audio Button playButton = findViewById(R.id.play_button); playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.start(); } }); // Set up stop button to stop audio Button stopButton = findViewById(R.id.stop_button); stopButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.stop(); mediaPlayer.reset(); try { mediaPlayer.setDataSource(audioFilePath); mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } } }); } @Override protected void onStop() { super.onStop(); // Release MediaPlayer resources mediaPlayer.release(); mediaPlayer = null; } } |
As you can see inside this java
code of the library we are using the MediaPlayer
class and it contains two methods which are start()
which starts the mp3
song and onStop
which stops it. And basically it make uses of the setDataSource()
method in which you need to specify or pass the audio song
uri as an argument.
And now we need to copy paste the below xml
code inside the activity_audio_player.xml
file and copy paste the below code
activity_audio_player.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/play_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Play" /> <Button android:id="@+id/stop_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" /> </LinearLayout> |