Open In App

How to Play Audio From URL in Android using Jetpack Compose?

Last Updated : 21 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Many apps require the feature to add the audio feature in their application and there are so many audio files that we have to play inside our application. If we will store so many audio files inside our application, then it will increase the size of the app and this may reduce the user base due to the huge app size. So the better way to tackle this problem is to store the audio files in your database and access them from their unique web URL. In this article, we will take a look at How to play audio from URL in Android using Jetpack Compose.

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. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color in the Color.kt file

Navigate to the app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. 

Kotlin




package com.example.newcanaryproject.ui.theme
 
import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 3: Adding internet permissions in AndroidManifest.xml

Navigate to app > manifest > AndroidManifest.xml file and add the below permission in the manifest tag. 

XML




<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.example.newcanaryproject
 
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import com.example.newcanaryproject.ui.theme.*
 
class MainActivity : ComponentActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line
                // we are specifying background color
                // for our application
                Surface(
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
 
                    // on below line we are specifying
                    // theme as scaffold.
                    Scaffold(
 
                        // in scaffold
                        // we are specifying top bar.
                        topBar = {
 
                            // inside top bar
                            // we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
 
                                // along with that we are specifying
                                // title for our top bar.
                                title = {
 
                                    // in the top bar we are specifying
                                    // tile as a text
                                    Text(
 
                                        // on below line we are specifying text
                                        // to display in top app bar.
                                        text = "Custom Toast in Android",
 
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
 
                                        // on below line we are specifying
                                        // text alignment.
                                        textAlign = TextAlign.Center,
 
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // on below line we are calling custom toast ui method
                        // to display ui for our custom toast
                        customToastUI()
                    }
                }
            }
        }
    }
}
 
// on below line we are creating a composable function
// to display ui for custom toast
@Composable
fun customToastUI() {
    // on below line we are creating a variable for context
    val ctx = LocalContext.current
    val mediaPlayer = MediaPlayer()
 
    // on below line we are creating a column for our ui.
    Column(
        // in this column we are adding a modifier
        // for our column and specifying max width, height and size.
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .fillMaxSize()
 
            // on below line we are adding padding
            // from all sides to our column.
            .padding(6.dp),
 
        // on below line we are adding vertical arrangement
        // for our column as bottom
        verticalArrangement = Arrangement.Center,
 
        // on below line we are adding horizontal alignment
        // for our column.
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // on below line we are
        // displaying a simple text
        Text(
 
            // on below line we are specifying
            // modifier as padding for our text.
            modifier = Modifier.padding(6.dp),
 
            // on below line we are specifying
            // text as normal image.
            text = "Play Audio from URL",
 
            // on below line we are specifying
            // font weight as bold.
            fontWeight = FontWeight.Bold,
 
            // on below line we are
            // setting color for our text
            color = greenColor,
 
            // on below line we are
            // setting font size.
            fontSize = 20.sp
        )
 
        // on below line we are creating a simple spacer
        // with height 20
        Spacer(modifier = Modifier.height(20.dp))
 
        // on below line we are creating a
        // button for displaying error toast
        Button(
            // on below line we are adding
            // width for our button and padding to it.
            modifier = Modifier
                .width(300.dp)
                .padding(7.dp),
 
            // in this button we are
            // adding on click for it on below line.
            onClick = {
 
                // 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(ctx, "Audio started playing..", Toast.LENGTH_SHORT).show()
 
            }) {
            // on below line we are specifying
            // text for button.
            Text(text = "Play Audio")
        }
 
        // on below line we are creating a spacer of height 20
        Spacer(modifier = Modifier.height(20.dp))
 
        // on below line we are
        // creating a button for displaying a toast
        Button(
            // on below line we are
            // adding width for our button and padding to it.
            modifier = Modifier
                .width(300.dp)
                .padding(7.dp),
 
            // in this button we are adding
            // on click for it on below line.
            onClick = {
                // 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(ctx, "Audio has been  paused..", Toast.LENGTH_SHORT).show()
                } else {
                    // if audio player is not displaying we are displaying
                    // below toast message
                    Toast.makeText(ctx, "Audio not played..", Toast.LENGTH_SHORT).show()
                }
 
 
            }) {
            // on below line we are specifying text for button.
            Text(text = "Pause Audio")
        }
 
 
    }
}


Now run your application to see the output of it. 

Output: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads