How to Play Audio From URL in Android using Jetpack Compose?
Last Updated :
21 Dec, 2022
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:
Similar Reads
How to Load Image From URL in Android using Jetpack Compose? Most of the applications in android use images for displaying some useful information within the applications. Images are considered as easy to convey information to the user. An android application uses more than 100 different types of images. So it is not practically possible to add all the images
4 min read
Play Audio in Android using Jetpack Compose In Android, a MediaPlayer is used to play media files like audio and video files in the application. The MediaPlayer Class uses the MediaPlayer API for performing various functions like creating a Media Player, playing, pausing, starting, and stopping the media. In this article, we will show you how
3 min read
How to Play Audio from URL in Android? Many apps require the feature to add the audio feature in their application and there 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 h
4 min read
How to Use Google Play Install Referrer API in Android using Jetpack Compose? Google Play Install Referrer is the API that is used in most of the applications but it is not seen in the application. This functionality works under the hood and is used to check the sources from where the app is getting most of the downloads. Google Play Install Referrer API tells us that from wh
6 min read
Play Audio From URL in Android using Kotlin 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 add
4 min read
Icon Toggle Button in Android using Jetpack Compose Toggle Buttons are used in most applications. These buttons are used to perform multiple operations. Toggle buttons are seen used in many social media applications such as Instagram. In social media apps, we can get to see a heart icon that is used to like the image. We can also unlike that image by
3 min read
How to Open an External URL on Button Click in Android using Jetpack compose? Many times in android applications we have to open a web page from an URL inside the default browser of the user's device. In that case, we have to simply pass that URL to the web browser to load that page. In this article, we will take a look at How to open a URL in an android web browser from our
5 min read
How to Post Data to API using Volley in Android using Jetpack Compose? APIs are used within Android Applications to interact with a database to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post data to API in android
3 min read
How to Post Data to API using Retrofit in Android using Jetpack Compose? APIs are used within Android Applications to interact with databases to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post Data to API using Retro
5 min read
How to Keep Device Screen On in Android using Jetpack Compose? Many times while building an android application we have to make sure that the user's device screen remains on. In the video player application, we can see that the user's device screen remains on until the video is not completed. For this, we have to keep the device screen on. In this article, we w
4 min read