Show me the code! – By Davanum Srinivas

Web Services, Apache, Websphere, IBM, etc.

Android – Video/Music player sample (from local disk as well as remote URL’s)

with 78 comments

Here is a screen shot.

1

Notes



  • You can specify a directory path or a remote URL in the edit box

  • You can specify just an mp3 file to play music only

  • Choose any 3gp file from http://daily3gp.com/ to view videos

  • The 4 buttons are for play, pause, reset and stop

  • When you specify a http or https url, we save the url contents to hard disk first and then play it

  • All the leg work was done by dahui. Many thanks!!

  • The icons are from here

  • MediaPlayer does not yet support any remote url’s or MPEG4 video AFAICT

Here’s the code


package org.apache.android;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.ImageButton;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class VideoPlayer extends Activity implements OnErrorListener,
        OnBufferingUpdateListener, OnCompletionListener,
        MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {
    private static final String TAG = "VideoPlayer";

    private MediaPlayer mp;
    private SurfaceView mPreview;
    private EditText mPath;
    private SurfaceHolder holder;
    private ImageButton mPlay;
    private ImageButton mPause;
    private ImageButton mReset;
    private ImageButton mStop;
    private String current;

    /**
     * Called when the activity is first created.
     */
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        setContentView(R.layout.main);

        // Set up the play/pause/reset/stop buttons
        mPreview = (SurfaceView) findViewById(R.id.surface);
        mPath = (EditText) findViewById(R.id.path);
        mPlay = (ImageButton) findViewById(R.id.play);
        mPause = (ImageButton) findViewById(R.id.pause);
        mReset = (ImageButton) findViewById(R.id.reset);
        mStop = (ImageButton) findViewById(R.id.stop);

        mPlay.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                playVideo();
            }
        });
        mPause.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (mp != null) {
                    mp.pause();
                }
            }
        });
        mReset.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (mp != null) {
                    mp.seekTo(0);
                }
            }
        });
        mStop.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (mp != null) {
                    mp.stop();
                    mp.release();
                }
            }
        });

        // Set the transparency
        getWindow().setFormat(PixelFormat.TRANSPARENT);

        // Set a size for the video screen
        holder = mPreview.getHolder();
        holder.setCallback(this);
        holder.setFixedSize(400, 300);
    }

    private void playVideo() {
        try {
            final String path = mPath.getText().toString();
            Log.v(TAG, "path: " + path);

            // If the path has not changed, just start the media player
            if (path.equals(current) && mp != null) {
                mp.start();
                return;
            }
            current = path;

            // Create a new media player and set the listeners
            mp = new MediaPlayer();
            mp.setOnErrorListener(this);
            mp.setOnBufferingUpdateListener(this);
            mp.setOnCompletionListener(this);
            mp.setOnPreparedListener(this);
            mp.setAudioStreamType(2);

            // Set the surface for the video output
            mp.setDisplay(mPreview.getHolder().getSurface());

            // Set the data source in another thread
            // which actually downloads the mp3 or videos
            // to a temporary location
            Runnable r = new Runnable() {
                public void run() {
                    try {
                        setDataSource(path);
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                    mp.prepare();
                    Log.v(TAG, "Duration:  ===>" + mp.getDuration());
                    mp.start();
                }
            };
            new Thread(r).start();
        } catch (Exception e) {
            Log.e(TAG, "error: " + e.getMessage(), e);
            if (mp != null) {
                mp.stop();
                mp.release();
            }
        }
    }

    /**
     * If the user has specified a local url, then we download the
     * url stream to a temporary location and then call the setDataSource
     * for that local file
     *
     * @param path
     * @throws IOException
     */
    private void setDataSource(String path) throws IOException {
        if (!URLUtil.isNetworkUrl(path)) {
            mp.setDataSource(path);
        } else {
            URL url = new URL(path);
            URLConnection cn = url.openConnection();
            cn.connect();
            InputStream stream = cn.getInputStream();
            if (stream == null)
                throw new RuntimeException("stream is null");
            File temp = File.createTempFile("mediaplayertmp", "dat");
            String tempPath = temp.getAbsolutePath();
            FileOutputStream out = new FileOutputStream(temp);
            byte buf[] = new byte[128];
            do {
                int numread = stream.read(buf);
                if (numread <= 0)
                    break;
                out.write(buf, 0, numread);
            } while (true);
            mp.setDataSource(tempPath);
            try {
                stream.close();
            }
            catch (IOException ex) {
                Log.e(TAG, "error: " + ex.getMessage(), ex);
            }
        }
    }

    public void onError(MediaPlayer mediaPlayer, int what, int extra) {
        Log.e(TAG, "onError--->   what:" + what + "    extra:" + extra);
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }

    public void onBufferingUpdate(MediaPlayer arg0, int percent) {
        Log.d(TAG, "onBufferingUpdate called --->   percent:" + percent);
    }

    public void onCompletion(MediaPlayer arg0) {
        Log.d(TAG, "onCompletion called");
    }

    public void onPrepared(MediaPlayer mediaplayer) {
        Log.d(TAG, "onPrepared called");
    }

    public boolean surfaceCreated(SurfaceHolder surfaceholder) {
        Log.d(TAG, "surfaceCreated called");
        return true;
    }

    public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
        Log.d(TAG, "surfaceChanged called");
    }

    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
        Log.d(TAG, "surfaceDestroyed called");
    }
}

Download Source and APK from here – VideoPlayer.zip

Written by Davanum Srinivas

December 29, 2007 at 11:25 pm

Posted in Uncategorized

78 Responses

Subscribe to comments with RSS.

  1. Hi,
    Thanks for your code, It works like a charm but i need to know one thing where the temp file is created and is it not necessary to delete the temp file every time when the media is completed

    Navas

    December 31, 2007 at 1:39 am

  2. Hi,

    I tried to run the code but I cannot import the project in Eclipse and when I create a new project and I try to copy the unzipped files over the created ones, some errors occur.

    Can you provide more informations on how to run this project?
    Thank you

    Liviu

    December 31, 2007 at 9:07 am

  3. [...] has also made the source available, which can be found here. SHARETHIS.addEntry({ title: “A New Media Player for Android”, url: [...]

  4. Hi,

    I download the application and unable to run the same in eclipse. It showing some exception in Androidmanifest.xml file.

    It showing “package ‘ org.apache.android’ does not exist! “. what i suppose to do for this.

    Thanks,
    Bala.

    Balaji

    January 24, 2008 at 5:03 am

  5. Hi,

    I have created one more file in that i added all the files present in the VideoPlayer.zip.

    Finally i got something, but with simple text box alone, nothin other than that is comming .

    Kindly help me in this regrds.

    Bala.

    Balaji

    January 24, 2008 at 6:07 am

  6. Hi,

    Is there any way to start video playback from a service?

    Rohit

    January 28, 2008 at 1:38 am

  7. Thanks for a great demo!
    Simple, elegant and well-written.

    Amos

    January 31, 2008 at 4:48 pm

  8. Hi,

    Could you please update this to work with M5.

    Thanks,

    Regards

    gary silva

    February 17, 2008 at 9:44 pm

  9. Very nice example. For those who have problem to run it:
    How it is written one will need to use HVGA-L mode of emulator or to edit the following line inside onCreate:
    holder.setFixedSize(400, 300);
    to something less ambitious like 200×200.

    Filip Bulovic

    February 24, 2008 at 1:45 pm

  10. Hi,
    Can you update this player to M5 please!

    Tanks.
    Andrew

    Andrew

    March 5, 2008 at 2:50 pm

  11. Thanks for a great demo!

    Deri

    March 23, 2008 at 1:06 pm

  12. Hi,
    Could you update this player to M5 please!
    thanks

    peng

    April 24, 2008 at 10:13 pm

  13. Hi .
    I can’t play the video from the local . the error as follows:
    Duration: ===> -1
    Could you help me check it .Thansk

    Thanks.

    peng

    April 28, 2008 at 2:35 am

  14. peng i am also gtting th same problem … as in Dalvik debug monitor showing th duration as -1

    Dinesh

    May 12, 2008 at 7:48 am

  15. hv u found the solution for tat .. if so help me out ..

    Dinesh

    May 12, 2008 at 7:49 am

  16. Hi,

    This code is showing some errors.
    Actually the setCallback method is not avalable in m5. And the surfaceCreated method’s return type has been changed.

    i updated these errors. but am not able toplay any file. Please help me.

    radhika

    May 13, 2008 at 7:29 am

  17. may i have a look at your main file? thanks!

    abc

    May 20, 2008 at 10:46 pm

  18. hi……

    i have the proble with the video view i will post my code down …….its not working…

    [syntax="java"]
    Java:
    import android.net.Uri;
    import android.os.Bundle;
    import android.widget.VideoView;
    public class musicplayer extends Activity {

    @Override
    public void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    setContentView(R.layout.main);
    VideoView vv=(VideoView)findViewById(R.id.vdoplayer);
    // MediaPlayer mp=new MediaPlayer();

    // Uri myUrl = Uri.parse(”http://207.210.108.32/Music/Crazy.3gp”);
    // vv.setVideoURI(myUrl);
    vv.setVideoPath(”http://207.210.108.32/Music/Alarm.wmv”);
    vv.start();

    }
    }

    this is the java file andd xml given below

    XML:
    ]syntax=”xml”]

    but is not working…..i was trying with the my own server….it is getting in browser….but not working with the video view…….can any body help me…….

    or can any body tell me how to access and play video on the emulator …..

    please…
    with thanks bins……..

    bins

    May 22, 2008 at 6:43 am

  19. Hi,
    thanks a lot for that example!
    1. I can play videos from the internet when i remove the extra thread and start & prepare the player without it. Do you really need an extra thread? The GUI is reacting nevertheless, so whats the advantage?
    2. How can i play local files? I put them into the resource folder (res/raw/), but no path which i enter in the textfield seem to be correct.

    thanks for help

    alex

    May 28, 2008 at 7:58 am

  20. Ok,
    i figured out a way to play local videos. If you play them from the Internet, they get stored in /tmp/… I just copied a video over eclipse FileExplorer into that directory and played the url /tmp/filename. But i don´t know how to play files within the resources directory. Most likely they are stored in the app.apk. Why can´t i play them with /res/raw/filenname?

    alex

    May 28, 2008 at 10:19 am

  21. Hi,
    This is really great and thanks for sharing this code. but
    can anybody tell me where is the zip file for this source code?

    else let me know how to run this code in android emulator?

    Thanks,
    Souvik

    souvik

    June 16, 2008 at 2:37 am

  22. Problem: Not able to load the project into Eclipse.
    when I want to add this project as new project from existing source and given the path for this folder , its showing an error msg:” No activity name defined in D:\android\android_workspace\VideoPlayer\AndroidManifest.xml.”

    and not able to load this project.
    Please help me to load this project to run it in emulator.
    Thanks,
    Souvik

    souvik

    June 16, 2008 at 4:03 am

  23. Hi,

    I could resolve all the errors. I’m finding problem at the run time. I’m getting NullPointerException error. Found that the error is due to
    mPreview = (SurfaceView) findViewById(R.id.surface)
    mPreview is null.
    Likewise, mPath, mPlay, … are also null.

    Can anyone suggest how to overcome this issue???????

    Celia

    celia

    June 20, 2008 at 4:02 am

  24. Hi, Change the id to android:id in main.xml.
    You will see the layout by the above modification.

    Prahlad T

    July 7, 2008 at 1:28 am

  25. hi there..
    from above pasted code.. when i did some changes at line number 122.. i just cut that line and put out of thread then only it is working fine for total video lenght.

    otherwise if i keep it as it is in thread then only very small fraction of video from initial part is playing then after it is terminating application…

    can you help me in that .,…?

    nekin

    July 9, 2008 at 5:43 am

  26. Does anybody here know a valid and updated code that works fine? :(

    ricardo souza

    July 15, 2008 at 7:21 am

  27. I have some problem on
    final String path = mPath.getText().toString();

    when I run the program..
    java.nullpointer exception occur..
    can someone help me?
    thx in advanced

    hendrik

    July 24, 2008 at 9:15 pm

  28. Hi!,

    name

    August 31, 2008 at 10:40 pm

  29. Hi,

    I can’t see the source code. I got web page not found exception if I’m trying to download the source code.

    Can you plz… anybody share the source code ?

    Thanks in advance.

    Yasmin

    October 20, 2008 at 10:53 pm

  30. The source and pictures are no longer available. If you still have the source, could you please email it to me ? Thank you !

    Tim

    October 24, 2008 at 11:25 am

  31. Hallo ,

    great Work ,but i can’t play it with the 0.9 Beta ,Could you please help me and mail me this .

    thanks

    Ami

    November 5, 2008 at 9:47 am

  32. hi,
    i cant able to download the code canu pls share the code

    i have copied and run it i am getting error

    MediaPLayer :Error(-38,0)
    Error(-1,0)
    will u pls help me ou of this

    thanxin advance

    babavali

    November 21, 2008 at 1:28 am

  33. hi,
    where is the source file? I got web page not found exception 404 whie downloading the source code.

    can anybody share the code pls….
    my id is alpesh.harsoda@gmail.com

    thnks in advance.

    Regards,
    Alpesh Harsoda

    Alpesh

    December 8, 2008 at 4:34 am

  34. Hi,
    I tried this code by make some necessary changes. but not working can you please help me. Its giving the NullPointerException at surface view,giving error(-38,0). Some where it showing Status=#fffffff

    ankit somani

    December 13, 2008 at 3:42 pm

  35. Can anybody share the source code?
    I couldn’t download the code.

    Please…

    my email is cindyduh@nthu.us

    thanks a lot!

    cindy

    December 18, 2008 at 7:45 am

  36. Please share the Video Player Code .. Since it is not downloadable from this site

    Nikhil

    January 25, 2009 at 3:52 am

  37. my email id is nikhilbhandary@gmail.com
    Please share the Video Player Code .. Since it is not downloadable from this site

    Nikhil

    January 25, 2009 at 3:56 am

  38. Can anybody please share the source code? The download link is not working. email: high2freq@yahoo.com

    Thanks.

    Andrea

    January 26, 2009 at 3:40 am

  39. Yes, I would appreciate the code also. My email is aphilsmith@gmail.com

    Thanks!

    Phil

    January 26, 2009 at 3:17 pm

  40. can you please email me the ZIP file as its no longer downloadable from this site?
    i desperately need it.

    anushka

    January 27, 2009 at 1:04 pm

  41. please email me the ZIP file as its no longer downloadable from this site?
    i desperately need it.

    anushka

    January 27, 2009 at 1:05 pm

  42. can anybody pleaseeeeeee email this file to me… as i’m not able to download the zip file from this site…PLeaseeeeee
    email : varsha.uni@gmail.com

    Varsha

    February 2, 2009 at 6:11 pm

  43. Many thanks to this code.

    The lik to zip file is not available. Is this been removed from the server?

    I am trying use the code mentioned above. I could not compile it. It saying R.ID is not recognized. Can someone give me strps to compile this code. What are other files needed or what declaration are needed to compile this successfully?

    Thank you for your time.

    vishy

    February 3, 2009 at 1:39 am

  44. Dear, Can some one share the code to update the Progress bar of the Media playback?

    vishy

    February 5, 2009 at 10:23 am

  45. Please share source code with me, as this has been removed from server. my email id is jayesh.thadani@gmail.com

    jayesh

    February 5, 2009 at 11:52 pm

  46. The link to the sourcecode does not exist. Can you share the latest zip file at pbdnit@yahoo.com pls ?

    Gate

    February 13, 2009 at 2:51 pm

  47. Can anybody please share the source code? The download link is not working. email: mrcararia@gmail.com

    Thanks.

    Mr. Cararia

    February 16, 2009 at 6:00 am

  48. Hey guyz.. plz i need this code .. so could u ppl send this code on this email add: javeeduddin.b@hotmail.com

    Javed

    February 20, 2009 at 12:14 am

  49. Can anybody please share the source code? The download link is not working. email: smartcelldebono@yahoo.com

    Thanks.

    Smartcell

    February 26, 2009 at 12:21 pm

  50. The download able zip code is not available on this link. can you pls send it to me in mail? muthusankarm@hotmail.com

    muthu

    March 3, 2009 at 6:44 am

  51. Hey, could you please send me(or update the download link) the source code of this app? I need it for a future-android-streaming app i’m developing. Thanks in advance! (Email: tdr.popa@gmail.com)

    tudor

    March 8, 2009 at 11:41 am

  52. Please share source code with me, as this has been removed from server. my email id is linesaver@gmail.com

    linesaver

    March 9, 2009 at 12:55 am

  53. some to me… where is the source :)
    please info to: ilovesinai@gmail.com

    chris

    March 9, 2009 at 4:32 am

  54. pls send me the source code to shaks@ureach.com

    shakeel

    March 10, 2009 at 10:09 pm

  55. Hi their,
    I would like to have the Video/Musik player, so please can anyone send me the source code. e-Mail: m.kruemmling@googlemail.com

    Michael

    March 25, 2009 at 9:15 am

  56. Please share source code with me, as this has been removed from server. my email id is devadrita.harh@gmail.com

    Devadrita

    March 28, 2009 at 1:14 pm

  57. cant download source from that link -.-” can u send to my email? embedzit@gmail.com

    thx lotz

    suesi tan

    March 30, 2009 at 3:43 am

  58. Hi, can’t download the Zip-File. Can pleas send me the code to gurkenlager@googlemail.com

    Thanks!!!

    Gurke

    April 2, 2009 at 8:37 am

  59. I can’t download the zip file from the link. Please send me the file to hsyun@sktelecom.com Thank you in avanced!

    Harrison

    April 23, 2009 at 2:13 am

  60. Please share the code to me at my email id: apanwar@live.com as it is not downloadable from the link.
    Thanks,
    Amit

    Amit Panwar

    April 24, 2009 at 9:53 am

  61. I can’t download the zip file from the link. Please send me the file to emily.ting@ecs.com.tw Thank you in avanced!

    emily

    April 29, 2009 at 7:41 am

  62. Hi,i’m starting learning android now and this is really helpful to me,thanks for making it public.

    Can i have the source code at fidevel@yahoo.com,since its not downloadable from the link?Thanks in advance!

    3m

    fidevel

    April 30, 2009 at 8:23 am

  63. nice work man can i have the source code at my email id
    here it is kl_jander@yahoo.com thanks

    ben

    May 1, 2009 at 4:40 am

  64. Can anybody please share the source code? I desperately need it. thanks.
    recl24@hotmail.com

    rudi

    May 4, 2009 at 1:50 am

  65. Can anybody please share the source code? I desperately need it. thanks.
    hinty_ollo@hotmail.com

    sabrina

    May 17, 2009 at 10:01 pm

  66. I can’t download source code. Please Share the source code..
    lakdong@hotmail.com

    ldsung

    May 18, 2009 at 1:34 am

  67. Can you please share the source code ? Thanks a lot !

    Jesslyn

    May 19, 2009 at 5:23 pm

  68. I can’t download source code. Please Share the source code..
    bhwon@pyroworks.co.kr

    bhwon

    May 20, 2009 at 12:47 am

  69. I can’t download source code. Please Share the source code. Thanks a lot.

    color47@gmail.com

    Color

    May 21, 2009 at 4:20 am

  70. Can somebody send source zip file to me?
    I am stuck with running live video streaming part :(
    TIA

    Aahna

    May 28, 2009 at 3:26 am

  71. Can you please share the source code ? Thanks a lot !

    poveteen

    June 1, 2009 at 10:28 pm

  72. Can you please share the source code ? Thanks a lot !

    poveteen@gmail.com

    poveteen

    June 1, 2009 at 10:29 pm

  73. other solution pages from davanum have the zip file downloadable. Any particular reason why this link is disabled?
    It would be great help if people who got it earlier upload the same zip somewhere and share the link for helping others.
    Regards,
    Aahna

    Aahna

    June 3, 2009 at 1:12 am

  74. Can anybody please share the source code? I desperately need it. thanks.

    shiihs5286@gmail.com

    Skono

    June 9, 2009 at 1:10 am

  75. I can’t download the zip file from the link. Please send me the file to shiihs5286@gmail.com Thank you in avanced!

    shiihs

    June 9, 2009 at 1:42 am

  76. hey hi buddy …
    cn i get source code of same.. it will be gr8 help fr me if i get code .. thnx in advance ..:)

    tushar

    June 9, 2009 at 9:35 am


Leave a Reply