Here is an example for playing audio files in mediaplayer. Mediaplayer.java package com.example.musicplayer; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import android.app.Activity; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; public class Mediaplayer extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener { private ImageButton Play; private ImageButton Forward; private ImageButton Backward; private ImageButton Next; private ImageButton Previous; private ImageButton Playlist; private SeekBar ProgressBar; private TextView TitleLabel; private TextView CurrentDurationLabel; private TextView TotalDurationLabel; // Media Player private MediaPlayer mp; // Handler to update UI timer, progress bar etc,. private Handler mHandler = new Handler();; private SongsManager songManager; private Utilities utils; private int seekForwardTime = 5000; // 5000 milliseconds private int seekBackwardTime = 5000; // 5000 milliseconds private int currentSongIndex = 0; private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.player); // All player buttons Play = (ImageButton) findViewById(R.id.btnPlay); Forward = (ImageButton) findViewById(R.id.btnForward); Backward = (ImageButton) findViewById(R.id.btnBackward); Next = (ImageButton) findViewById(R.id.btnNext); Previous = (ImageButton) findViewById(R.id.btnPrevious); Playlist = (ImageButton) findViewById(R.id.btnPlaylist); ProgressBar = (SeekBar) findViewById(R.id.songProgressBar); TitleLabel = (TextView) findViewById(R.id.songTitle); CurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel); TotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel); // Mediaplayer mp = new MediaPlayer(); songManager = new SongsManager(); utils = new Utilities(); // Listeners ProgressBar.setOnSeekBarChangeListener(this); // Important mp.setOnCompletionListener(this); // Important // Getting all songs list songsList = songManager.getPlayList(); // By default play first song playSong(0); Play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // check for already playing if(mp.isPlaying()){ if(mp!=null){ mp.pause(); // Changing button image to play button Play.setImageResource(R.drawable.img_btn_play); } }else{ // Resume song if(mp!=null) { mp.start(); Play.setImageResource(R.drawable.img_btn_pause); } } } }); Forward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // get current song position int currentPosition = mp.getCurrentPosition(); // check if seekForward time is lesser than song duration if(currentPosition + seekForwardTime <= mp.getDuration()){ // forward song mp.seekTo(currentPosition + seekForwardTime); }else{ // forward to end position mp.seekTo(mp.getDuration()); } } }); Backward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // get current song position int currentPosition = mp.getCurrentPosition(); // check if seekBackward time is greater than 0 sec if(currentPosition - seekBackwardTime >= 0){ // forward song mp.seekTo(currentPosition - seekBackwardTime); }else{ // backward to starting position mp.seekTo(0); } } }); Next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // check if next song is there or not if(currentSongIndex < (songsList.size() - 1)){ playSong(currentSongIndex + 1); currentSongIndex = currentSongIndex + 1; }else{ // play first song playSong(0); currentSongIndex = 0; } } }); Previous.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if(currentSongIndex > 0){ playSong(currentSongIndex - 1); currentSongIndex = currentSongIndex - 1; }else{ // play last song playSong(songsList.size() - 1); currentSongIndex = songsList.size() - 1; } } }); Playlist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent(getApplicationContext(), PlayListActivity.class); startActivityForResult(i, 100); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == 100){ currentSongIndex = data.getExtras().getInt("songIndex"); // play selected song playSong(currentSongIndex); } } public void playSong(int songIndex){ // Play song try { mp.reset(); mp.setDataSource(songsList.get(songIndex).get("songPath")); mp.prepare(); mp.start(); // Displaying Song title String songTitle = songsList.get(songIndex).get("songTitle"); TitleLabel.setText(songTitle); // Changing Button Image to pause image Play.setImageResource(R.drawable.img_btn_pause); // set Progress bar values ProgressBar.setProgress(0); ProgressBar.setMax(100); // Updating progress bar updateProgressBar(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void updateProgressBar() { mHandler.postDelayed(mUpdateTimeTask, 100); } private Runnable mUpdateTimeTask = new Runnable() { public void run() { long totalDuration = mp.getDuration(); long currentDuration = mp.getCurrentPosition(); // Displaying Total Duration time TotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration)); // Displaying time completed playing CurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration)); // Updating progress bar int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration)); //Log.d("Progress", ""+progress); ProgressBar.setProgress(progress); // Running this thread after 100 milliseconds mHandler.postDelayed(this, 100); } }; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { // remove message Handler from updating progress bar mHandler.removeCallbacks(mUpdateTimeTask); } @Override public void onStopTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); int totalDuration = mp.getDuration(); int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration); // forward or backward to certain seconds mp.seekTo(currentPosition); // update timer progress again updateProgressBar(); } @Override public void onCompletion(MediaPlayer arg0) { if(currentSongIndex < (songsList.size() - 1)){ playSong(currentSongIndex + 1); currentSongIndex = currentSongIndex + 1; }else{ // play first song playSong(0); currentSongIndex = 0; } } @Override public void onDestroy(){ super.onDestroy(); mp.release(); } } Playlist.java package com.example.musicplayer; import java.util.ArrayList; import java.util.HashMap; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; public class PlayListActivity extends ListActivity { // Songs list public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.playlist); ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>(); SongsManager plm = new SongsManager(); // get all songs from sdcard this.songsList = plm.getPlayList(); // looping through playlist for (int i = 0; i < songsList.size(); i++) { // creating new HashMap HashMap<String, String> song = songsList.get(i); // adding HashList to ArrayList songsListData.add(song); } // Adding menuItems to ListView ListAdapter adapter = new SimpleAdapter(this, songsListData, R.layout.playlist_item, new String[] { "songTitle" }, new int[] { R.id.songTitle }); setListAdapter(adapter); // selecting single ListView item ListView lv = getListView(); // listening to single listitem click lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting listitem index int songIndex = position; // Starting new intent Intent in = new Intent(getApplicationContext(), Mediaplayer.class); // Sending songIndex to PlayerActivity in.putExtra("songIndex", songIndex); setResult(100, in); // Closing PlayListView finish(); } }); } } Songsmanager.java package com.example.musicplayer; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.HashMap; public class SongsManager { // SDCard Path final String MEDIA_PATH = new String("/sdcard/"); private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); // Constructor public SongsManager(){ } public ArrayList<HashMap<String, String>> getPlayList(){ File home = new File(MEDIA_PATH); if (home.listFiles(new FileExtensionFilter()).length > 0) { for (File file : home.listFiles(new FileExtensionFilter())) { HashMap<String, String> song = new HashMap<String, String>(); song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4))); song.put("songPath", file.getPath()); // Adding each song to SongList songsList.add(song); } } // return songs list array return songsList; } class FileExtensionFilter implements FilenameFilter { public boolean accept(File dir, String name) { return (name.endsWith(".mp3") || name.endsWith(".MP3")); } } } Utilities.java package com.example.musicplayer; public class Utilities { /** * Function to convert milliseconds time to * Timer Format * Hours:Minutes:Seconds * */ public String milliSecondsToTimer(long milliseconds){ String finalTimerString = ""; String secondsString = ""; // Convert total duration into time int hours = (int)( milliseconds / (1000*60*60)); int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60); int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000); // Add hours if there if(hours > 0){ finalTimerString = hours + ":"; } // Prepending 0 to seconds if it is one digit if(seconds < 10){ secondsString = "0" + seconds; }else{ secondsString = "" + seconds;} finalTimerString = finalTimerString + minutes + ":" + secondsString; // return timer string return finalTimerString; } /** * Function to get Progress percentage * */ public int getProgressPercentage(long currentDuration, long totalDuration){ Double percentage = (double) 0; long currentSeconds = (int) (currentDuration / 1000); long totalSeconds = (int) (totalDuration / 1000); // calculating percentage percentage =(((double)currentSeconds)/totalSeconds)*100; // return percentage return percentage.intValue(); } /** * Function to change progress to timer * returns current duration in milliseconds * */ public int progressToTimer(int progress, int totalDuration) { int currentDuration = 0; totalDuration = (int) (totalDuration / 1000); currentDuration = (int) ((((double)progress) / 100) * totalDuration); // return current duration in milliseconds return currentDuration * 1000; } } player.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:background="#000000"> <LinearLayout android:id="@+id/player_header_bg" android:layout_width="fill_parent" android:layout_height="60dip" android:background="#000000" android:layout_alignParentTop="true" android:paddingLeft="5dp" android:paddingRight="5dp"> <TextView android:id="@+id/songTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textColor="#04b3d2" android:textSize="16dp" android:paddingLeft="10dp" android:textStyle="bold" android:text="Song Title " android:layout_marginTop="10dp"/>" <ImageButton android:id="@+id/btnPlaylist" android:layout_width="50dip" android:layout_height="50dip" android:src="@drawable/playllist" android:background="@null"/> </LinearLayout> <LinearLayout android:id="@+id/songThumbnail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="10dp" android:paddingBottom="10dp" android:gravity="center" android:layout_below="@id/player_header_bg"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/music"/> </LinearLayout> <LinearLayout android:id="@+id/player_footer_bg" android:layout_width="fill_parent" android:layout_height="100dp" android:layout_alignParentBottom="true" android:background="#6E6E6E" android:gravity="center"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical" android:background="@layout/rounded_corner" android:paddingLeft="10dp" android:paddingRight="10dp"> <ImageButton android:id="@+id/btnPrevious" android:src="@drawable/img_btn_previous" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null"/> <ImageButton android:id="@+id/btnBackward" android:src="@drawable/img_btn_backward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null"/> <ImageButton android:id="@+id/btnPlay" android:src="@drawable/img_btn_play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null"/> <ImageButton android:id="@+id/btnForward" android:src="@drawable/img_btn_forward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null"/> <ImageButton android:id="@+id/btnNext" android:src="@drawable/img_btn_next" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null"/> </LinearLayout> </LinearLayout> <SeekBar android:id="@+id/songProgressBar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:layout_marginBottom="20dp" android:layout_above="@id/player_footer_bg" android:thumb="@drawable/seek_handler" android:progressDrawable="@drawable/seekbar_progress" android:paddingLeft="6dp" android:paddingRight="6dp"/> <LinearLayout android:id="@+id/timerDisplay" android:layout_above="@id/songProgressBar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:layout_marginBottom="10dp"> <TextView android:id="@+id/songCurrentDurationLabel" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="left" android:textColor="#eeeeee" android:textStyle="bold"/> <TextView android:id="@+id/songTotalDurationLabel" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="right" android:textColor="#04cbde" android:textStyle="bold"/> </LinearLayout> </RelativeLayout> playlist.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:divider="#242424" android:dividerHeight="1dp" /> </LinearLayout> playlist_item.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" android:padding="5dp"> <TextView android:id="@+id/songTitle" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="16dp" android:padding="10dp" android:color="#f3f3f3"/> </LinearLayout> rounded corner.xml <?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#2b2b2b"/> <stroke android:width="1dp" android:color="#242424" /> <padding android:left="1dp" android:top="1dp" android:right="1dp" android:bottom="1dp" /> <corners android:bottomRightRadius="40dp" android:bottomLeftRadius="40dp" android:topLeftRadius="40dp" android:topRightRadius="40dp"/> </shape> Screenshot
Friday, 9 November 2012
Mediaplayer in Android
Subscribe to:
Posts (Atom)