
- Android Basics
- Android - Home
- Android - Overview
- Android - Environment Setup
- Android - Architecture
- Android - Application Components
- Android - Hello World Example
- Android - Resources
- Android - Activities
- Android - Services
- Android - Broadcast Receivers
- Android - Content Providers
- Android - Fragments
- Android - Intents/Filters
- Android - User Interface
- Android - UI Layouts
- Android - UI Controls
- Android - Event Handling
- Android - Styles and Themes
- Android - Custom Components
- Android Advanced Concepts
- Android - Drag and Drop
- Android - Notifications
- Location Based Services
- Android - Sending Email
- Android - Sending SMS
- Android - Phone Calls
- Publishing Android Application
- Android Useful Examples
- Android - Alert Dialoges
- Android - Animations
- Android - Audio Capture
- Android - AudioManager
- Android - Auto Complete
- Android - Best Practices
- Android - Bluetooth
- Android - Camera
- Android - Clipboard
- Android - Custom Fonts
- Android - Data Backup
- Android - Developer Tools
- Android - Emulator
- Android - Facebook Integration
- Android - Gestures
- Android - Google Maps
- Android - Image Effects
- Android - ImageSwitcher
- Android - Internal Storage
- Android - JetPlayer
- Android - JSON Parser
- Android - Linkedin Integration
- Android - Loading Spinner
- Android - Localization
- Android - Login Screen
- Android - MediaPlayer
- Android - Multitouch
- Android - Navigation
- Android - Network Connection
- Android - NFC Guide
- Android - PHP/MySQL
- Android - Progress Circle
- Android - ProgressBar
- Android - Push Notification
- Android - RenderScript
- Android - RSS Reader
- Android - Screen Cast
- Android - SDK Manager
- Android - Sensors
- Android - Session Management
- Android - Shared Preferences
- Android - SIP Protocol
- Android - Spelling Checker
- Android - SQLite Database
- Android - Support Library
- Android - Testing
- Android - Text to Speech
- Android - TextureView
- Android - Twitter Integration
- Android - UI Design
- Android - UI Patterns
- Android - UI Testing
- Android - WebView Layout
- Android - Wi-Fi
- Android - Widgets
- Android - XML Parsers
- Android Useful Resources
- Android - Questions and Answers
- Android - Useful Resources
- Android - Discussion
MediaPlayer class to implement a basic Audio Player in an Android App
This example demonstrates how do I create a Mediaplayer class to implement a basic audio player in android app.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="10dp" android:paddingRight="10dp"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Now Playing: " android:layout_marginTop="30dp" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/txtSongName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView" android:layout_toEndOf="@+id/textView" /> <ImageButton android:id="@+id/btnBackward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="44dp" android:layout_marginLeft="20dp" android:src="@drawable/ic_back" /> <ImageButton android:id="@+id/btnPlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/btnBackward" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/btnBackward" android:src="@drawable/ic_play" /> <ImageButton android:id="@+id/btnPause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/btnPlay" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/btnPlay" android:src="@drawable/ic_pause" /> <ImageButton android:id="@+id/btnForward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/btnPause" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/btnPause" android:contentDescription="@+id/imageButton3" android:src="@drawable/ic_forward" /> <TextView android:id="@+id/txtStartTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/seekBar" android:text="0 min, 0 sec" /> <SeekBar android:id="@+id/seekBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/btnBackward" android:layout_toLeftOf="@+id/txtSongTime" android:layout_toRightOf="@+id/txtStartTime" /> <TextView android:id="@+id/txtSongTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/btnForward" android:layout_alignTop="@+id/seekBar" android:text="0 min, 0 sec " /> </RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.media.MediaPlayer; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity { private ImageButton forwardBtn, backwardBtn, pauseBtn, playBtn; private MediaPlayer mediaPlayer; private TextView songName, startTime, songTime; private SeekBar songProgress; private static int onTime =0, playTime =0, endTime =0, forwardTime = 5000, backwardTime = 5000; private Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); backwardBtn = findViewById(R.id.btnBackward); forwardBtn = findViewById(R.id.btnForward); playBtn = findViewById(R.id.btnPlay); pauseBtn = findViewById(R.id.btnPause); songName = findViewById(R.id.txtSongName); startTime = findViewById(R.id.txtStartTime); songTime = findViewById(R.id.txtSongTime); songName.setText("Bohemian_Rhapsody"); mediaPlayer = MediaPlayer.create(this, R.raw.bohemian_rhapsody); songProgress = findViewById(R.id.seekBar); songProgress.setClickable(false); pauseBtn.setEnabled(false); playBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Playing Audio", Toast.LENGTH_SHORT).show(); mediaPlayer.start(); endTime = mediaPlayer.getDuration(); playTime = mediaPlayer.getCurrentPosition(); if (onTime == 0) { songProgress.setMax(endTime); onTime = 1; } songTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(endTime), TimeUnit.MILLISECONDS.toSeconds(endTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(endTime)))); startTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(playTime), TimeUnit.MILLISECONDS.toSeconds(playTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(playTime)))); songProgress.setProgress(playTime); handler.postDelayed(UpdateSongTime, 100); pauseBtn.setEnabled(true); playBtn.setEnabled(false); } }); pauseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.pause(); pauseBtn.setEnabled(false); playBtn.setEnabled(true); Toast.makeText(getApplicationContext(), "Pausing Audio", Toast.LENGTH_SHORT).show(); } }); forwardBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ((playTime + forwardTime) <= endTime) { playTime = playTime + forwardTime; mediaPlayer.seekTo(playTime); } else { Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show(); } if (!playBtn.isEnabled()) { playBtn.setEnabled(true); } } }); backwardBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ((playTime - backwardTime) > 0) { playTime = playTime - backwardTime; mediaPlayer.seekTo(playTime); } else { Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show(); } if (!playBtn.isEnabled()) { playBtn.setEnabled(true); } } }); } private Runnable UpdateSongTime = new Runnable() { @Override public void run() { playTime = mediaPlayer.getCurrentPosition(); startTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(playTime), TimeUnit.MILLISECONDS.toSeconds(playTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(playTime))) ); songProgress.setProgress(playTime); handler.postDelayed(this, 100); } }; }
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <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/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
- Related Articles
- MediaPlayer class to implement a basic Audio Player in an Android Kotlin app?
- How to embed youtube as an audio player?
- How to add an audio player to an HTML webpage?
- How to implement an Android notification action without opening the app?
- Basic Prerequisites of Learning Android app development
- How to implement the Drag and Drop functionality over a Recycler View in an Android App ?
- JavaScript to parse and show current time stamp of an HTML audio player.
- Audio Manager in Android
- HTML5 audio not playing in PhoneGap App
- How to create a gridView layout in an Android app?
- How to create a multilevel ListView in an Android app?
- How to create TextToSpeech in an android app?
- How to integrate PayPal in an Android app?
- How to use calendar widget using the calendarView class in Android App?
- How to create a custom alert dialogs in an android app?
