MediaPlayer cannot play downloaded mp3 file


Last Updated:

  1. duykienvp

    duykienvp New Member This Topic's Starter

    Joined:
    Oct 23, 2010
    Messages:
    3
    Likes Received:
    0
    My application gets playlist from a XML file, requests URL of mp3 file from server, downloads and plays it.
    It was able to download mp3 file but unable to play it.
    When I used emulator with Android 2.1, it was displayed in LogCat:
    Mp3 file downloaded, exists and has length but MediaPlayer couldn't play it.
    This happened at setDataSource() method.

    When I used emulator with Android 2.2, it could be prepared but MediaPlayer still couldn't play it with error (1, -2147483648).

    When I used my download method to download that file and saved to my hard disk, Window Media Player could play normally.

    I have googled for many days but nothing works.

    Please help.

    Code (Text):
    1. package org.me.androidmediaplayer;
    2.  
    3. import android.app.Activity;
    4. import android.media.MediaPlayer;
    5. import android.os.Bundle;
    6. import android.util.Log;
    7.  
    8. import android.view.View;
    9. import android.view.View.OnClickListener;
    10. import android.widget.*;
    11. import android.widget.AdapterView.OnItemClickListener;
    12.  
    13. import java.io.*;
    14. import java.net.HttpURLConnection;
    15. import java.net.URL;
    16. import java.net.URLConnection;
    17.  
    18. import javax.xml.parsers.DocumentBuilder;
    19. import javax.xml.parsers.DocumentBuilderFactory;
    20.  
    21. import org.apache.http.HttpResponse;
    22. import org.apache.http.client.methods.HttpGet;
    23. import org.apache.http.impl.client.DefaultHttpClient;
    24. import org.w3c.dom.Document;
    25. import org.w3c.dom.Element;
    26. import org.w3c.dom.Node;
    27. import org.w3c.dom.NodeList;
    28.  
    29. /**
    30.  * Music Player
    31.  * @author Duy Kien
    32.  */
    33. public class AndroidMediaPlayer extends Activity {
    34.     //song list Url
    35.     private final String songListUrl =
    36.                             "http://aladdins.vn/nghenhac/playlist.xml";
    37.     //server Url
    38.     private final String serverUrl =
    39.                             "http://aladdins.vn/nghenhac/getMusic.do";
    40.  
    41.     //views of layout
    42.     private ImageButton ibtnStop, ibtnPlayPause, ibtnReset;
    43.     private TextView tvPlayPause, tvStatus;
    44.     private ListView lvPlaylist;
    45.  
    46.     //media player to play mp3 files
    47.     private MediaPlayer mp;
    48.  
    49.     //songs list
    50.     private int nSongs = 0;
    51.     private int[] iSongID;
    52.     private String[] sSongID;
    53.     private String[] songs;
    54.     private ArrayAdapter<String> songList;
    55.    
    56.     //list of temp file path
    57.     private String[] filePaths;
    58.  
    59.     //boolean array to check if a song downloaded before
    60.     boolean[] downloaded;
    61.  
    62.     //file to store mp3 file received from server
    63.     private String musicFile;
    64.  
    65.     //log string
    66.     private static final String TAG = "---AndroidMediaPlayer";
    67.  
    68.     /** Called when the activity is first created. */
    69.     @Override
    70.     public void onCreate( Bundle icicle ) {
    71.         super.onCreate( icicle );
    72.         setContentView( R.layout.main );
    73.  
    74.         mp = new MediaPlayer();
    75.  
    76.         //take views of layout
    77.         getViews();
    78.  
    79.         //get playlist from server
    80.         getPlaylist( songListUrl );
    81.  
    82.         //create array adapter for ListView
    83.         songList = new ArrayAdapter<String>( this.getApplicationContext(),
    84.                                              R.layout.list_item,
    85.                                              songs );
    86.         lvPlaylist.setAdapter( songList );
    87.         lvPlaylist.setVisibility(ListView.VISIBLE);
    88.  
    89.         //initialize
    90.         downloaded = new boolean[ nSongs ];
    91.         for (int i = 0; i < downloaded.length; i++)
    92.             downloaded[i] = false;
    93.  
    94.         filePaths = new String[ nSongs ];
    95.     } //end onCreate
    96.  
    97.     /**
    98.      * Take views of layout
    99.      */
    100.     private void getViews() {
    101.         //find views from layout
    102.         tvPlayPause   = (TextView)    findViewById ( R.id.tvPlayPause );
    103.         tvStatus      = (TextView)    findViewById ( R.id.tvStatus );
    104.         ibtnStop      = (ImageButton) findViewById ( R.id.ibtnStop );
    105.         ibtnPlayPause = (ImageButton) findViewById ( R.id.ibtnPlayPause );
    106.         ibtnReset       = (ImageButton) findViewById ( R.id.ibtnReset );
    107.         lvPlaylist    = (ListView)    findViewById ( R.id.lvSongs );
    108.  
    109.         //Stop button
    110.         ibtnStop.setOnClickListener(new OnClickListener() {
    111.             public void onClick(View view) {
    112.                 mp.stop();
    113.                 tvStatus.setText("Stopped");
    114.                 tvPlayPause.setText(R.string.play);
    115.                 ibtnPlayPause.setImageResource(R.drawable.play);
    116.             } //end onClick
    117.         }); //end setOnClickListener
    118.  
    119.         //Play or Pause button        
    120.         ibtnPlayPause.setOnClickListener(new OnClickListener(){
    121.             public void onClick(View view) {
    122.                 //if current text is "Play"
    123.                 //then play music and change textview and image
    124.                 //else
    125.                 //then stop music and change textview and image                  
    126.                 if ( tvPlayPause.getText().equals("Pause")) {
    127.                     tvStatus.setText( "Paused" );
    128.                     tvPlayPause.setText( R.string.play );
    129.                     ibtnPlayPause.setImageResource( R.drawable.play );
    130.                     mp.pause();                  
    131.                 } //end if
    132.                
    133.                 else {
    134.                         Log.i(TAG, "tvPlayPause text = " + tvPlayPause.getText());
    135.                     tvStatus.setText( "Playing..." );
    136.                     tvPlayPause.setText( R.string.pause );
    137.                         Log.i(TAG, "tvPlayPause text changed to: " + tvPlayPause.getText());
    138.                     ibtnPlayPause.setImageResource( R.drawable.pause );
    139.                     mp.start();
    140.                 } //end else
    141.             } // end onClick
    142.         });//end setOnClickListener
    143.  
    144.         //Reset button
    145.         ibtnReset.setOnClickListener( new OnClickListener () {
    146.             public void onClick ( View view )
    147.             {
    148.                 mp.seekTo(0);
    149.             } //end onClick
    150.         }); //end setOnClickListener
    151.  
    152.         //List view Playlist
    153.         lvPlaylist.setOnItemClickListener(new PlaylistClick());
    154.     } //end getViews
    155.  
    156.     /**
    157.      * Get songs list from given Url
    158.      * @param Url
    159.      */
    160.     private void getPlaylist( String url ) {
    161.         //input stream for reading content of Url
    162.         HttpURLConnection httpConnection;
    163.         InputStream inStream    = null;
    164.        
    165.         try {
    166.             //create a connection from given Url
    167.             httpConnection = createHttpConnection( url );
    168.             if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
    169.                 inStream = httpConnection.getInputStream();
    170.  
    171.             //xml file contains song List
    172.             Document xmlSongList = null;
    173.  
    174.             //builder to build xml file
    175.             DocumentBuilder db;
    176.             DocumentBuilderFactory dbf =
    177.                     DocumentBuilderFactory.newInstance();
    178.  
    179.             db          = dbf.newDocumentBuilder();
    180.             xmlSongList = db.parse( inStream );
    181.  
    182.             xmlSongList.getDocumentElement().normalize();
    183.  
    184.             //retrieve all <song> node
    185.             NodeList playlistNode  = xmlSongList.getElementsByTagName( "playList" );
    186.             Element root            = (Element) playlistNode.item(0);
    187.             NodeList songNodes     = root.getElementsByTagName("song");
    188.             nSongs = songNodes.getLength();
    189.             iSongID = new int[ nSongs ];
    190.             sSongID = new String[ nSongs ];
    191.             songs = new String[ nSongs ];
    192.            
    193.             //retrive song information
    194.             for (int i = 0; i < nSongs; i++) {
    195.                 Element songNode = (Element) songNodes.item( i );
    196.                
    197.                 //get song title
    198.                 Node titleNode = (Node) songNode.getElementsByTagName("title").item(0);
    199.                 Node titleNodeValue = titleNode.getFirstChild();
    200.                 songs[ i ]       = titleNodeValue.getNodeValue();
    201.  
    202.                 //get song ID
    203.                 Node idNode      = (Node) songNode.getElementsByTagName("id").item(0);
    204.                 Node idNodeValue = idNode.getFirstChild();
    205.                 sSongID[ i ]     = idNodeValue.getNodeValue();
    206.                 iSongID[ i ]     = Integer.parseInt( sSongID[ i ] );
    207.             } //end for
    208.             httpConnection.disconnect();
    209.             inStream.close();
    210.         } // end try
    211.         catch (Exception ex) {
    212.             ex.printStackTrace();
    213.         } //end catch      
    214.     }//end getPlaylist
    215.  
    216.     /**
    217.      * Create an HttpConnection from given Url
    218.      * @param Url URL to make connection
    219.      * @return HttpURLConnection from Url in HTTP form
    220.      */
    221.     private HttpURLConnection createHttpConnection(String urlString)
    222.             throws IOException {
    223.        
    224.         HttpURLConnection httpConnection;
    225.  
    226.         try {      
    227.             //open connection from given URL
    228.             URL url = new URL(urlString);
    229.             URLConnection connection = url.openConnection();
    230.        
    231.             if (!(connection instanceof HttpURLConnection ))
    232.                 throw new IOException("Not a HTTP connection");
    233.            
    234.             //connect to url in HTTP form
    235.             httpConnection = (HttpURLConnection) connection;
    236.             httpConnection.setAllowUserInteraction(false);
    237.             httpConnection.setInstanceFollowRedirects(true);
    238.             httpConnection.setRequestMethod("GET");
    239.             httpConnection.connect();
    240.            
    241.         } //end try  
    242.         catch (IOException ex) {
    243.             throw ex;
    244.         } // end catch        
    245.        
    246.         return httpConnection;
    247.     } //end createHttpConnection
    248.  
    249.     /**
    250.      * Perform action when a track is clicked
    251.      * @author Duy Kien
    252.      *
    253.      */
    254.     class PlaylistClick implements OnItemClickListener {
    255.  
    256.         public void onItemClick(AdapterView<?> list, View view,
    257.                               int position, long id) {
    258.            
    259.             Log.i(TAG, "play track at " + (position + 1));
    260.            
    261.             /*
    262.             try {
    263.                 mp = new MediaPlayer();
    264.                 mp.setDataSource(getFileUrl(position));
    265.                 mp.prepare();
    266.             } //end try
    267.             catch (Exception ex) {
    268.                 ex.printStackTrace();
    269.             } //end catch
    270.             */
    271.            
    272.             //if this song was downloaded before
    273.             if ( downloaded[ position ] ) {
    274.                 musicFile = filePaths[ position ];
    275.             } //end if
    276.             ////if this song was NOT downloaded before
    277.             else {
    278.                 tvStatus.setText( "Downloading..." );
    279.                
    280.                     Log.i(TAG, "Downloading...");
    281.                
    282.                 tvStatus.postInvalidate();
    283.                
    284.                 musicFile = downloadFile( position );
    285.                
    286.                     Log.i(TAG, "musicFile = " + musicFile);
    287.                    
    288.                 tvStatus.setText( "Download completed" );
    289.                 tvStatus.postInvalidate();
    290.                
    291.                 //remember that this track is downloaded
    292.                 downloaded[ position ] = true;
    293.                 filePaths[ position ]  = musicFile;
    294.             } //end else
    295.            
    296.             //prepare to play
    297.             try {
    298.                 FileInputStream fis = new FileInputStream( musicFile );
    299.                 File newFile         = new File( musicFile );
    300.                     Log.i(TAG, "musicFile exist = " + newFile.exists());
    301.                     Log.i(TAG, "music file length = " + newFile.length());
    302.                 mp.setDataSource( fis.getFD(), 0, newFile.length() );
    303.                 mp.prepare();
    304.                    
    305.                     Log.i(TAG, "prepared music file");      
    306.             } // end try
    307.             catch (Exception ex){
    308.                 ex.printStackTrace();
    309.             } //end catch
    310.         }      //end onItenClick
    311.     }           //end PlaylistClick
    312.  
    313.     /**
    314.      * Download mp3 file with given ID from server
    315.      * @param id id of mp3 file to download
    316.      * @return path to temporary file
    317.      */
    318.     private String downloadFile(int id) {
    319.         String fileUrl  = "";
    320.         String filePath = null;
    321.        
    322.         try {
    323.             //get URL of mp3 file
    324.             fileUrl = getFileUrl(id);
    325.                 Log.i(TAG, "fileUrl = " + fileUrl);
    326.  
    327.             //create input stream for downloading file
    328.             HttpURLConnection connection = createHttpConnection(fileUrl);
    329.            
    330.             InputStream inStream = null;
    331.             if (connection.getResponseCode() == HttpURLConnection.HTTP_OK)
    332.                 inStream = connection.getInputStream();
    333.             DataInputStream dataInputStream = new DataInputStream(inStream);
    334.            
    335.             //create temp file
    336.             File temp = File.createTempFile("track" + String.valueOf(id),
    337.                                                 ".mp3");
    338.             temp.deleteOnExit();
    339.             filePath = temp.getAbsolutePath();
    340.                 Log.i(TAG, "begin download file: " + filePath);
    341.  
    342.             FileOutputStream outFile = new FileOutputStream(temp);
    343.  
    344.             int bufferSize = 1024;
    345.             byte buffer[]  = new byte[ bufferSize ];
    346.  
    347.             do {
    348.                 int numberRead = dataInputStream.read(buffer);
    349.                 if (numberRead <= 0)
    350.                     break;
    351.                 outFile.write(buffer, 0, numberRead);
    352.                
    353.                 buffer = new byte[ bufferSize ];
    354.             } while (true);
    355.  
    356.             //close connection
    357.             dataInputStream.close();
    358.             inStream.close();
    359.             connection.disconnect();
    360.            
    361.             outFile.flush();
    362.             outFile.close();
    363.                 Log.i(TAG, "downloaded : " + filePath);
    364.         } //end try
    365.         catch (Exception ex){
    366.             ex.printStackTrace();
    367.         } // end catch
    368.  
    369.         return filePath;
    370.     } //end downloadFile
    371.    
    372.     /**
    373.      * Get URL of clicked track from server
    374.      * @param id id of clicked track
    375.      * @return URL of clicked track
    376.      */
    377.     private String getFileUrl(int id) {
    378.         String fileUrl = "";
    379.         String request = serverUrl;
    380.        
    381.         try {
    382.             //instantiate a HTTP Client
    383.             DefaultHttpClient client = new DefaultHttpClient();
    384.  
    385.             //add request parameter
    386.             request += ( "?id=0" + (id + 1));
    387.            
    388.             //instantiate a HTTP method
    389.             HttpGet method = new HttpGet(request);
    390.        
    391.             //execute GET method
    392.             HttpResponse response =  client.execute(method);
    393.          
    394.             //get response and retrieve file URL
    395.             InputStream dataResponse = response.getEntity().getContent();
    396.          
    397.             DataInputStream inStream = new DataInputStream( dataResponse );
    398.            
    399.             inStream.readShort();
    400.             inStream.read();
    401.             fileUrl = inStream.readUTF();
    402.            
    403.             //close connection
    404.             inStream.close();
    405.         } //end try
    406.         catch (Exception ex) {
    407.             ex.printStackTrace();
    408.            
    409.         } //end catch
    410.         return fileUrl;
    411.     }//end getFileUrl
    412. } //end AndroidMediaPlayer
    413.  
    414.  
     

    Advertisement
  2. sitlet

    sitlet Banned

    Joined:
    Apr 11, 2010
    Messages:
    5,867
    Likes Received:
    633
    does the track have drm?
     
  3. duykienvp

    duykienvp New Member This Topic's Starter

    Joined:
    Oct 23, 2010
    Messages:
    3
    Likes Received:
    0
    :( sorry, but what does drm mean?
     
  4. sitlet

    sitlet Banned

    Joined:
    Apr 11, 2010
    Messages:
    5,867
    Likes Received:
    633
    Digital Rights management. Basically all mp3s bought from itunes store have drm, which only allows them to be played in itunes or an ipod.
     
  5. duykienvp

    duykienvp New Member This Topic's Starter

    Joined:
    Oct 23, 2010
    Messages:
    3
    Likes Received:
    0
    I just downloaded that mp3 file from a web server and i couldn't find drm inside it.

    I've googled for many days and really exhausted :(.

    I dont know how to solve this........
     
  6. sitlet

    sitlet Banned

    Joined:
    Apr 11, 2010
    Messages:
    5,867
    Likes Received:
    633
    the only thing that you are doing differently than anyone else, is the way you are fetching them from a server. Since nothing else seems to be wrong, I would have to say thats your problem. Have you tried putting the files on the phone manually just to see if they play?
     

Share This Page

Loading...