In this android example tutorial we will see how to play list of audio files using Media Player in Android Studio using Kotlin language.
What is Media Player?
In Android, the MediaPlayer Class is used to play media files. Those are audio and video files, respectively. It can also be used to stream audio or video across the network.
Implementation:
Step 1: Create a new Project in android studio.
Go to File > New > New Project > Empty Activity > Next > Enter Name > Select Language Kotlin > Finish |
Step 2: Open activity_main.xml file and add the recyclerview Widget.
<androidx.recyclerview.widget.RecyclerView |
Android RecyclerView is a more flexible and adaptable variant of ListView and GridView. It is a container for presenting a huge number of data sets that may be scrolled very efficiently by keeping a restricted number of views.
Step3: Create a new xml file
app > res > layout > right-click > new > layout resource file > Enter file name (audio_layout) > Ok. |
Step 4: Open audio_layout.xml file and add the following code.
<?xml version="1.0" encoding="utf-8"?>
<TextView </LinearLayout> |
The above xml code will show you given output:
Step 5: Create a new Kotlin file (AudioModel) and add the following code
class AudioModel { constructor(songUrl: String) { } |
Step 6: Create a adapter kotlin class (AudioAdapter) and add the following kotlin code
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { override fun onBindViewHolder(holder: ViewHolder, position: Int) { } else { // If music is playing this line will stop it //Toast is used to show that music has paused } override fun getItemCount() = audioList.size private fun playAudio(audioUrl: String) { mediaPlayer.setAudioAttributes(
|
Step 7: Go to MainActivity.kt file
Initialize the recylerview and AudioAdapter class instance
lateinit var rv: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { |
Create a new arrayList of AudioModel type
var list = ArrayList() |
Add song url in List
list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")) |
Set list data in adapter and set adapter in recyclerView
adapter = AudioAdapter(this, list) |
Step 8: Final step, go to AndroidManifest.xml file and add the following permissions.
<uses-permission android:name="android.permission.INTERNET" /> |
Step 9: Now run the app in your emulator or real device, you will get the given output
OUTPUT:
Complete Source Code of Youtube Video Player Example:
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <androidx.recyclerview.widget.RecyclerView </LinearLayout> |
MainActivity.kt file
import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { fun loadtracks() { adapter = AudioAdapter(this, list) } } |
audio_layout.xml file
<?xml version="1.0" encoding="utf-8"?> <TextView <TextView </LinearLayout> |
AudioModel.kt file
class AudioModel { constructor(songUrl: String) { } |
AudioAdapter.kt file
import android.content.Context
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { override fun onBindViewHolder(holder: ViewHolder, position: Int) { } else { Toast.makeText(requireContext, "Audio has been paused", Toast.LENGTH_SHORT) } override fun getItemCount() = audioList.size private fun playAudio(audioUrl: String) { mediaPlayer.setAudioAttributes(
|
AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?> <application <category android:name="android.intent.category.LAUNCHER" /> </manifest> |
Conclusion: In this example we have covered how to play list of music files using Media Player in Android Studio using Kotlin Language.
Related
Android Get Bitmap from Drawable resources
Android Ratate Image with Animation
Android add Math Equations with Latex code
<?xml version="1.0" encoding="utf-8"?>
The above xml code will show you given output:
Step 5: Create a new Kotlin file (AudioModel) and add the following code
class AudioModel { var songUrl: String? = null constructor(songUrl: String) { this.songUrl = songUrl } } |
Step 6: Create a adapter kotlin class (AudioAdapter) and add the following kotlin code
class AudioAdapter(val requireContext: Context, val audioList: ArrayList) : RecyclerView.Adapter() { lateinit var mediaPlayer: MediaPlayer inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val title = itemView.findViewById(R.id.tvTitle) val btnplay = itemView.findViewById(R.id.btnPlay) val icon = itemView.findViewById(R.id.icon) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(requireContext).inflate(R.layout.audio_layout, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val audio = audioList[position] val no = position+1 holder.title.setText("Song " + no) holder.btnplay.setOnClickListener { val audioUrl = audio.songUrl if (audioUrl != null) { if (holder.btnplay.text.equals("Play")) { playAudio(audioUrl) holder.btnplay.text = "Pause" holder.icon.setBackgroundResource(R.drawable.pause) } else { // If music is playing this line will stop it mediaPlayer.stop() mediaPlayer.reset() mediaPlayer.release() //Toast is used to show that music has paused Toast.makeText(requireContext, "Audio has been paused", Toast.LENGTH_SHORT) .show() holder.btnplay.text = "Play" holder.icon.setBackgroundResource(R.drawable.play) } } } } override fun getItemCount() = audioList.size private fun playAudio(audioUrl: String) { mediaPlayer = MediaPlayer() mediaPlayer.setAudioAttributes( AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build() ) try { // below line is use to set our url to our media player. mediaPlayer.setDataSource(audioUrl) // below line is use to prepare // and start our media player. mediaPlayer.prepareAsync() mediaPlayer.setOnPreparedListener(OnPreparedListener { mp -> // This line is used to play the music mp.start() }) } catch (e: Exception) { e.printStackTrace() } // below line is use to display a toast message. Toast.makeText(requireContext, "Audio started playing..", Toast.LENGTH_SHORT).show() } } |
Step 7: Go to MainActivity.kt file
Initialize the recylerview and AudioAdapter class instance
lateinit var rv: RecyclerView lateinit var adapter: AudioAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) rv = findViewById(R.id.rv) // Used to set the recyclerview data in vertical direction rv.layoutManager = LinearLayoutManager(this) |
Create a new arrayList of AudioModel type
var list = ArrayList() |
Add song url in List
list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")) list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3")) list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3")) list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-13.mp3")) list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-16.mp3")) |
Set list data in adapter and set adapter in recyclerView
adapter = AudioAdapter(this, list) rv.adapter = adapter |
Step 8: Final step, go to AndroidManifest.xml file and add the following permissions.
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> |
Step 9: Now run the app in your emulator or real device, you will get the given output
OUTPUT:
Complete Source Code of Youtube Video Player Example:
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rv" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> |
MainActivity.kt file
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { lateinit var rv: RecyclerView lateinit var adapter: AudioAdapter var list = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) rv = findViewById(R.id.rv) rv.layoutManager = LinearLayoutManager(this) loadtracks() } fun loadtracks() { list.clear() list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")) list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3")) list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3")) list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-13.mp3")) list.add(AudioModel("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-16.mp3")) adapter = AudioAdapter(this, list) rv.adapter = adapter } } |
audio_layout.xml file
<?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="wrap_content" android:layout_marginTop="10dp" android:background="#B8BEE3" android:orientation="horizontal" android:padding="16dp"> <ImageView android:id="@+id/icon" android:layout_width="28dp" android:layout_height="28dp" android:background="@drawable/play"></ImageView> <TextView android:id="@+id/tvTitle" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:text="Song 1" android:textSize="21sp" android:textStyle="bold"></TextView> <TextView android:id="@+id/btnPlay" android:layout_width="70dp" android:layout_height="wrap_content" android:gravity="center" android:background="@color/purple_200" android:text="Play" android:textSize="20sp" /> </LinearLayout> |
AudioModel.kt file
class AudioModel { var songUrl: String? = null constructor(songUrl: String) { this.songUrl = songUrl } } |
AudioAdapter.kt file
import android.content.Context import android.media.MediaPlayer import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.recyclerview.widget.RecyclerView import java.lang.Exception import android.media.AudioAttributes import android.media.MediaPlayer.OnPreparedListener class AudioAdapter(val requireContext: Context, val audioList: ArrayList) : RecyclerView.Adapter() { lateinit var mediaPlayer: MediaPlayer inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val title = itemView.findViewById(R.id.tvTitle) val btnplay = itemView.findViewById(R.id.btnPlay) val icon = itemView.findViewById(R.id.icon) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(requireContext).inflate(R.layout.audio_layout, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val audio = audioList[position] val no = position+1 holder.title.setText("Song " + no) holder.btnplay.setOnClickListener { val audioUrl = audio.songUrl if (audioUrl != null) { if (holder.btnplay.text.equals("Play")) { playAudio(audioUrl) holder.btnplay.text = "Pause" holder.icon.setBackgroundResource(R.drawable.pause) } else { mediaPlayer.stop() mediaPlayer.reset() mediaPlayer.release() Toast.makeText(requireContext, "Audio has been paused", Toast.LENGTH_SHORT) .show() holder.btnplay.text = "Play" holder.icon.setBackgroundResource(R.drawable.play) } } } } override fun getItemCount() = audioList.size private fun playAudio(audioUrl: String) { mediaPlayer = MediaPlayer() mediaPlayer.setAudioAttributes( AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build() ) try { // below line is use to set our url to our media player. mediaPlayer.setDataSource(audioUrl) // below line is use to prepare // and start our media player. mediaPlayer.prepareAsync() mediaPlayer.setOnPreparedListener(OnPreparedListener { mp -> mp.start() }) } catch (e: Exception) { e.printStackTrace() } // below line is use to display a toast message. Toast.makeText(requireContext, "Audio started playing..", Toast.LENGTH_SHORT).show() } } |
AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.audioplayerkotlin"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AudioPlayerKotlin"> <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> |
Conclusion: In this example we have covered how to play list of music files using Media Player in Android Studio using Kotlin Language.
Related
Android Get Bitmap from Drawable resources
Android Ratate Image with Animation
Android add Math Equations with Latex code
-->
Article Contributed By :
|
|
|
|
3353 Views |