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
Android Architecture
Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern
5 min read
Architecture of 8085 microprocessor
A microprocessor is fabricated on a single integrated circuit (IC) or chip that is used as a central processing unit (CPU).The 8085 microprocessor is an 8-bit microprocessor that was developed by Intel in the mid-1970s. It was widely used in the early days of personal computing and was a popular cho
11 min read
States of a Process in Operating Systems
In an operating system, a process is a program that is being executed. During its execution, a process goes through different states. Understanding these states helps us see how the operating system manages processes, ensuring that the computer runs efficiently. Please refer Process in Operating Sys
11 min read
Android Tutorial
In this Android Tutorial, we cover both basic and advanced concepts. So whether you are a fresher (graduate) or an experienced candidate with several years of Android Development experience, you can follow this Android tutorial to kick-start your journey in Android app development. Our Android Tutor
15+ min read
Activity Lifecycle in Android with Demo App
In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when
9 min read
Introduction to Android Development
Android operating system is the largest installed base among various mobile platforms across the globe. Hundreds of millions of mobile devices are powered by Android in more than 190 countries of the world. It conquered around 71% of the global market share by the end of 2021, and this trend is grow
5 min read
Android UI Layouts
Layouts in Android define the user interface and hold UI controls or widgets that appear on the screen of an application. Every Android application consists of View and ViewGroup elements. Since an application contains multiple activitiesâeach representing a separate screenâevery activity has multip
5 min read
Top 50 Android Interview Questions and Answers - SDE I to SDE III
A Linux-based open-source OS, Android was created by Andy Rubin and became one of the most popular smartphone operating systems. With 71 percent of the market share worldwide, Android is on top. Because it is on top in the smartphone OS, Android development is always in demand.If you are seeking a j
15+ min read
Components of an Android Application
There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the appâs metadata, its hardware confi
3 min read
What is Intent in Android?
In Android, it is quite usual for users to witness a jump from one application to another as a part of the whole process, for example, searching for a location on the browser and witnessing a direct jump into Google Maps or receiving payment links in Messages Application (SMS) and on clicking jumpin
4 min read