Tuesday, September 4, 2012

Code for Audio Player in Android


Hello Friends,

Today I am going to share a sample application in Android for Audio Player, it will search all mp3 file in sd-card and fill it in a List and when we click one of them its start playing.

1-Manifest.xml 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhub4you.audio.player"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidhub4you.audio.player.AudioPlayerDemoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2-AudioPlayerDemoActivity.java

package com.androidhub4you.audio.player;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;


/**
 *
 * @author Manish
 *  http://www.androidhub4you.com/2012/09/code-for-audio-player-in-android.html#ixzz3Triz2VNq
 */

    public class AudioPlayerDemoActivity extends ListActivity{
        private final String MEDIA_PATH = new String("/sdcard/");
        private List<String> songs = new ArrayList<String>();
        private MediaPlayer mp = new MediaPlayer();
        private int currentPosition = 0;
        ArrayAdapter<String> songList;

        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.activity_audio_player_demo);
            updateSongList();
        }

        //get the song list from sd-card
        public void updateSongList() {
            File home = new File(MEDIA_PATH);
            if (home.listFiles(new MyMP3Filter()).length > 0) {
                for (File file : home.listFiles(new MyMP3Filter())) {
                    songs.add(file.getName());
                }
                songList = new ArrayAdapter<String>(this,R.layout.item, songs);
                setListAdapter(songList);
                //play the song from playSong method here we are passing song path to play
                playSong(MEDIA_PATH + songs.get(currentPosition));
               
            }
        }

        //method play song
        private void playSong(String songPath) {
            try {
                mp.reset();
                mp.setDataSource(songPath);
                mp.prepare();
                mp.start();
                // Setup listener so next song starts automatically
                mp.setOnCompletionListener(new OnCompletionListener() {
                    public void onCompletion(MediaPlayer arg0) {
                        nextSong();
                    }
                });
            } catch (IOException e) {
                Log.v(getString(R.string.app_name), e.getMessage());
            }
        }

        //method to play next song from the list if size is grater than current
        private void nextSong() {
            if (++currentPosition >= songs.size()) {
                // Last song, just reset currentPosition
                currentPosition = 0;
            } else {
                // Play next song
                playSong(MEDIA_PATH + songs.get(currentPosition));
            }
        }

    }

3- MyMP3Filter.java

 package com.androidhub4you.audio.player;

import java.io.File;
import java.io.FilenameFilter;
/**
 *
 * @author Manish
 *  http://www.androidhub4you.com/2012/09/code-for-audio-player-in-android.html#ixzz3Triz2VNq
 */
class MyMP3Filter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3"));
    }
}

4- main.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@id/android:title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Android Audio Player"/>
<ListView
android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView
android:id="@id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="No songs in SD Card."/>
</LinearLayout>

5-item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/songText"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

DOWNLOAD ZIP CODE

Thanks,
Manish

19 comments:

  1. Replies
    1. No Softy, this is working code. Do you have mp3 songs in your sdcard? at same location which path you given in your code?

      Delete
  2. Replies
    1. Try updated code-
      https://github.com/manishsri01/AudioPlayerDemo

      Delete
  3. the player doesn't work, songs don't play

    ReplyDelete
    Replies
    1. You guys have any song in your sdcard at "/sdcard/" location with .mp3 extension?

      Delete
    2. Try updated code-
      https://github.com/manishsri01/AudioPlayerDemo

      Delete
  4. Please check again your code. It's not working! Thanks!

    ReplyDelete
    Replies
    1. You guys have any song in your sdcard at "/sdcard/" location with .mp3 extension?

      Delete
    2. Anyway let me check I will update you and will try to provide github link to you.

      Delete
    3. Try updated code-
      https://github.com/manishsri01/AudioPlayerDemo

      Delete
  5. This is the error getting generated please check your codes its not working



    08-07 16:48:39.774: E/AndroidRuntime(17697): FATAL EXCEPTION: main
    08-07 16:48:39.774: E/AndroidRuntime(17697): Process: com.androidhub4you.audio.player, PID: 17697
    08-07 16:48:39.774: E/AndroidRuntime(17697): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhub4you.audio.player/com.androidhub4you.audio.player.AudioPlayerDemoActivity}: java.lang.NullPointerException: Attempt to get length of null array
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.app.ActivityThread.access$900(ActivityThread.java:177)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.os.Handler.dispatchMessage(Handler.java:102)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.os.Looper.loop(Looper.java:145)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.app.ActivityThread.main(ActivityThread.java:5942)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at java.lang.reflect.Method.invoke(Native Method)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at java.lang.reflect.Method.invoke(Method.java:372)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
    08-07 16:48:39.774: E/AndroidRuntime(17697): Caused by: java.lang.NullPointerException: Attempt to get length of null array
    08-07 16:48:39.774: E/AndroidRuntime(17697): at com.androidhub4you.audio.player.AudioPlayerDemoActivity.updateSongList(AudioPlayerDemoActivity.java:39)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at com.androidhub4you.audio.player.AudioPlayerDemoActivity.onCreate(AudioPlayerDemoActivity.java:33)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.app.Activity.performCreate(Activity.java:6283)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    08-07 16:48:39.774: E/AndroidRuntime(17697): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
    08-07 16:48:39.774: E/AndroidRuntime(17697): ... 10 more

    ReplyDelete
  6. Replies
    1. are you using real android phone not emulator? you must have some songs at given location in sd-card. And if still it is white please check your log cat and let us know the error.

      Delete