Open In App

Play Audio From URL in Android using Kotlin

Last Updated : 28 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Many applications want to add different types of audio files to their android applications. These audio files are played using a media player within the android application. We can play audio files within the android application from different sources by playing audio from a web URL or by simply adding an audio file within our android application. In this article, we will be taking a look at How to play audio from a URL in an android application in Kotlin. 

Note: If you are looking to play audio from a URL in your android application using Java. Check out the following article: How to play audio from URL  in android application using Java

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--on below line we are creating
        a text for heading of our app-->
    <TextView
        android:id="@+id/idTVExtracter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:gravity="center"
        android:padding="4dp"
        android:text="Play Audio from URL"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="18sp"
        android:textStyle="bold" />
 
 
    <!--on below line we are creating an
         image button for playing our audio-->
    <ImageButton
        android:id="@+id/idIBPlay"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:background="@android:color/transparent"
        android:src="@drawable/ic_play"
        android:tint="@color/black" />
 
    <!--on below line we are creating image
         button for pausing our audio-->
    <ImageButton
        android:id="@+id/idIBPause"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_below="@id/idIBPlay"
        android:layout_centerHorizontal="true"
        android:background="@android:color/transparent"
        android:src="@drawable/ic_pause"
        android:tint="@color/black" />
 
</RelativeLayout>


Step 3: Adding permissions to the AndroidManifest.xml file

As we are playing audio from URL in android. So we will have to add Internet permissions to load the URL. Add below permissions to the AndroidManifest.xml file.

XML




<!-- Permissions of internet -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Step 4: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Bundle
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating
    // variable for both of our image buttons.
    lateinit var playIB: ImageButton
    lateinit var pauseIB: ImageButton
    lateinit var mediaPlayer: MediaPlayer
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // on below line we are initializing
        // our buttons with id.
        playIB = findViewById(R.id.idIBPlay)
        pauseIB = findViewById(R.id.idIBPause)
 
        // on below line we are
        // initializing our media player
        mediaPlayer = MediaPlayer()
 
        playIB.setOnClickListener {
 
            // on below line we are creating a variable for our audio url
            var audioUrl = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
 
            // on below line we are setting audio stream
            // type as stream music on below line.
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
 
            // on below line we are running a try
            // and catch block for our media player.
            try {
                // on below line we are setting audio
                // source as audio url on below line.
                mediaPlayer.setDataSource(audioUrl)
 
                // on below line we are
                // preparing our media player.
                mediaPlayer.prepare()
 
                // on below line we are
                // starting our media player.
                mediaPlayer.start()
 
            } catch (e: Exception) {
 
                // on below line we are handling our exception.
                e.printStackTrace()
            }
            // on below line we are displaying a toast message as audio player.
            Toast.makeText(applicationContext, "Audio started playing..", Toast.LENGTH_SHORT).show()
 
        }
 
        pauseIB.setOnClickListener {
            // on below line we are checking
            // if media player is playing.
            if (mediaPlayer.isPlaying) {
                // if media player is playing we
                // are stopping it on below line.
                mediaPlayer.stop()
 
                // on below line we are resetting
                // our media player.
                mediaPlayer.reset()
 
                // on below line we are calling
                // release to release our media player.
                mediaPlayer.release()
 
                // on below line we are displaying a toast message to pause audio/
                Toast.makeText(applicationContext, "Audio has been  paused..", Toast.LENGTH_SHORT)
                    .show()
 
            } else {
                // if audio player is not displaying we are displaying below toast message
                Toast.makeText(applicationContext, "Audio not played..", Toast.LENGTH_SHORT).show()
            }
 
        }
    }
}


Now run your application to see the output of it. 

Output: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads