How to play .pls in android? - android

Android Media Player:
I'm able to play .mp3 file from URL.
While playing .pls getting eroor.
Code:
try{
String url=".pls url";
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
}catch(Exception
System.out.println("## Exception while playing: "+e);
mediaPlayer .release();
mediaPlayer = null;
}
Error:
09-12 12:44:04.026: E/MediaPlayer(704): error (1, -2147483648)
09-12 12:44:04.026: I/System.out(704): ## Exception while playing: java.io.IOException: Prepare failed.: status=0x1

If by pls you mean playlist information file, then mediaplayer cannot handle pls files.
.pls files are not media files. So you cannot play .pls files. Usually .pls are handled by the app and app extracts the information from the pls file and play the music file to which pls is pointing to.

String musicUlrPath;
LinkedList<String> streamingUrlList;
streamingUrlList=new LinkedList<String>();
ExecuteArrayList executeArrayList=new ExecuteArrayList();
executeArrayList.execute("blank");
class ExecuteArrayList extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
streamingUrlList=getStreamingUrl(pathFromJson);//you are geting path during json response
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
musicUlrPath=(streamingUrlList.get(0));
}
}
public LinkedList<String> getStreamingUrl(String url) {
Log.i(LOGTAG, "get streaming url");
final BufferedReader br;
String murl = null;
LinkedList<String> murls = null;
try {
URLConnection mUrl = new URL(url).openConnection();
br = new BufferedReader(
new InputStreamReader(mUrl.getInputStream()));
murls = new LinkedList<String>();
while (true) {
try {
String line = br.readLine();
if (line == null) {
break;
}
murl = parseLine(line);
if (murl != null && !murl.equals("")) {
murls.add(murl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(LOGTAG, "url to stream :" + murl);
return murls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
now set the extracted path
mediaPlayer.setDataSource(musicUlrPath);

Extract pls file in notepad , It will show like this
playlist]
File1=Alternative\everclear -URL
Title1=Everclear - So Much For The Afterglow
Length1=233
File2=Comedy\Weird Al - Everything You Know Is Wrong.mp3
.
.
NumberOfEntries=5
Version=2.
Use that URL in Media player.It will work.

Related

android, Read content of 100-300 files from FTP folder... Hangs

I am using RetrieveFilestream method with BufferedInputStream in a for loop. I am closing all
streams after processing each file and also adding ftp complete pending command.
Every thing works as expected in my test environment with few files. But in realtime data where there are 200-300 files, it hangs somewhere.
It is not throwing any exception making it difficult to debug. Cannot debug one by one. Any help?
Here is my code Block.
public String LoopThroughFiles(FTPClient myftp, String DirectoryName)
{
boolean flag=false;
String output="";
InputStream inStream=null;
BufferedInputStream bInf= null;
StringBuilder mystring = new StringBuilder();
progressBar = (ProgressBar) findViewById(R.id.progressBar);
try {
flag= myftp.changeWorkingDirectory(DirectoryName);
if(flag==true)
{
FTPFile[] files = myftp.listFiles();
progressBar.setMax(files.length);
String fname="";
myftp.enterLocalPassiveMode();
if(files.length > 0)
{
int n=0;
for (FTPFile file : files)
{
n=n+1;
int r= progressBar.getProgress();
progressBar.setProgress(r+n);
fname=file.getName();
// String path= myftp.printWorkingDirectory();
if(fname.indexOf("txt") != -1)
{
inStream = myftp.retrieveFileStream(fname);
int reply = myftp.getReplyCode();
if (inStream == null || (!FTPReply.isPositivePreliminary(reply) && !FTPReply.isPositiveCompletion(reply))) {Log.e("error retrieving file",myftp.getReplyString()); }
bInf=new BufferedInputStream (inStream);
int bytesRead;
byte[] buffer=new byte[1024];
String fileContent=null;
while((bytesRead=bInf.read(buffer))!=-1)
{
fileContent=new String(buffer,0,bytesRead);
mystring.append(fileContent);
}
mystring.append(",");
bInf.close();
inStream.close();
boolean isSucess= myftp.completePendingCommand();
if(isSucess == false)
Log.e("error retrieving file","Failed to retrieve the stream for " + fname);
}
}
flag= myftp.changeToParentDirectory();
}
}
}
catch (java.net.UnknownHostException e) {
e.printStackTrace();
Log.e("readfile,UnknownHost",e.getMessage());
}
catch (java.io.IOException e) {
e.printStackTrace();
Log.e("readfile,IO",e.getMessage());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,General",e.getMessage());
}
finally
{
try {
output = mystring.toString();
if(bInf != null)
bInf.close();
if(inStream != null)
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,finallyblock",e.getMessage());
}
}
return output;
}

Android stream m3u radio fails on mobile data (g3/mobile data)

Not very easy to explain:
I have this app for streaming online radio. The problem was first with m3u format (which android somehow cannot normally stream like pls), so I have to parse the url with this ParserM3UToURL (that I found somewhere)... like this:
Uri u = Uri.parse(ParserM3UToURL.parse(STREAM_URL, sdkVersion, c));
player = MediaPlayer.create(c, u);
Mostly it works ok but it has one bug...
I'm testing this on two devices one old 2.2.2. (api level 17), other 4.3 (api level 23). Older device works fine. It can stream radio over wifi or mobile data, but the newer device has some problem with streaming over mobile data (on wifi it works ok). The application crashes because the parse function returns null: http://pastebin.com/ghbAqGzM
And I assume there are many more phones with 4.x than 2.x android. Which of course is very painful for me. Somehow I have to fix this.. So I really hope somebody will have some clue about this. I hope my explanation was not to confusing...
This is the ParserM3UToURL.parse() function:
public static String parse(String paramString, int sdkVersion, Context c)
{
try
{
StrictModeWrapper.init(c);
HttpURLConnection localHttpURLConnection = (HttpURLConnection)new URL(paramString).openConnection();
InputStream localInputStream = localHttpURLConnection.getInputStream();
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));
StringBuffer localStringBuffer = new StringBuffer();
while (true)
{
String str = localBufferedReader.readLine();
if (str == null)
{
localHttpURLConnection.disconnect();
localBufferedReader.close();
localInputStream.close();
break;
}
if (str.contains("http"))
{
localHttpURLConnection.disconnect();
localBufferedReader.close();
localInputStream.close();
return str;
}
localStringBuffer.append(str);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
Below is what i worked on to stream radio (m3Urls). The example below uses a service. When the service is started, the url is parsed. Note that in the onPostExecute, parsed file is prepared. Once the file is prepared(completed buffering), the file is played/started and stopped upon completion.
public class BackgroundRadioService extends Service implements
OnCompletionListener, OnPreparedListener{
MediaPlayer mediaPlayer;
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
parseM3uUrlAndPrepare("http://listen.radionomy.com/andalousse.m3u");
return START_STICKY;
}
private void parseM3uUrlAndPrepare(final String url){
AsyncTask<String, Integer, String> asyn = new AsyncTask<String, Integer, String>(){
HttpClient httpClient;
HttpGet getRequest;
HttpResponse httpResponse = null;
String filePath = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
httpClient = new DefaultHttpClient();
getRequest = new HttpGet(url);
}
#Override
protected String doInBackground(String... params) {
try {
httpResponse = httpClient.execute(getRequest);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(httpResponse != null)
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
} else {
InputStream inputStream = null;
try {
inputStream = httpResponse.getEntity().getContent();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
//Log.v("PLAYLISTLINE", "ORIG: " + line);
if (line.startsWith("#")) { // Metadata
} else if (line.length() > 0) {
filePath = "";
if (line.startsWith("http://")) { // Assume it's a full URL
filePath = line;
} else { // Assume it's relative
try{
filePath = getRequest.getURI().resolve(line).toString();
}catch(IllegalArgumentException e){
}catch(Exception e){
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return filePath;
}
#Override
protected void onPostExecute(String filePath) {
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepareAsync(); //this will prepare file a.k.a buffering
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
asyn.execute("");
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
}//end of Service class declaration
Note: This ignores playlists hence assumes the m3u parsed will return only one file. Let me know if you would like to handle playlists so I modify my answer :)
I solved it thanks to this question's comments: POST request failing when in 3G
The problem was actually with proxies on 3G. So if proxies are disabled, no weird http requests.
I modified my code a little. Thanks to Nana's answer I no longer need a m3u parser. I also no longer use HttpClient but HttpURLConnection instead. So when calling URL.openConnection() I add the Proxy.NO_PROXY parameter to that function and bam!
So the solution is "use HttpURLConnection not HttpClient and add NO_PROXY parameter":
conn = (HttpURLConnection) the_url.openConnection( Proxy.NO_PROXY );

Android Run class on new thread [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
NetworkOnMainThread
(3 answers)
Closed 9 years ago.
I am trying to parse .pls file to get urls to play. I used following code, but it is giving networkonmainthread exception. I never did threaded apps before; How can I run this class on new thread?
public class GetStreamingUrl {
private static String LOGTAG = "GetStreamingUrl";
private Context mContext;
public String url1;
public LinkedList<String> url2;
public GetStreamingUrl(Context context) {
Log.i(LOGTAG, "call to constructor");
this.mContext = context;
}
public LinkedList<String> getStreamingUrl(String url) {
Log.i(LOGTAG, "get streaming url");
final BufferedReader br;
String murl = null;
LinkedList<String> murls = null;
try {
URLConnection mUrl = new URL(url).openConnection();
br = new BufferedReader(
new InputStreamReader(mUrl.getInputStream()));
murls = new LinkedList<String>();
while (true) {
try {
String line = br.readLine();
if (line == null) {
break;
}
murl = parseLine(line);
if (murl != null && !murl.equals("")) {
murls.add(murl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(LOGTAG, "url to stream :" + murl);
return murls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
}
I am trying to parse .pls file to get urls to play. I used following code, but it is giving networkonmainthread exception. I never did threaded apps before; How can I run this class on new thread?
Just do this:
new Thread(new Runnable() {
#Override
public void run() {
// DO YOUR STUFFS HERE
}
}).start();
Hope this helps.
You can use AsyncTask and do the work inside it. Follow the link below for more details:
http://developer.android.com/reference/android/os/AsyncTask.html

Play midi file in an asynctask on Android

Here is how my app works:
After the app received the music it will first save the file into the SD card and then play it.
I tried to play the music with an asynctask called by a class (not an activity but a handler). However, the music can be played for only 1-2 seconds. Here is the code for the call back of AsyncTask:
fos = new FileOutputStream(file);
fos.write(receivedMusicPayload);
fos.flush();
fos.close();
PlayMusicManager pmm = new PlayMusicManager(qrC);
pmm.execute();
and here is the playermanager:
public class PlayMusicManager extends AsyncTask<Void, Void, Void> {
private QRConnection qrC;
public PlayMusicManager(QRConnection qrC) {
this.qrC = qrC;
}
#Override
protected Void doInBackground(Void... params) {
MediaPlayer mediaPlayer = new MediaPlayer();
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "music.mid");
if (file.exists()) // check if file exist
{
FileInputStream fis;
try {
fis = new FileInputStream(file);
FileDescriptor fd = fis.getFD();
mediaPlayer.setDataSource( fd);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
qrC.getQrActivity().showResult("No such file");
}
return null;
}
#Override
protected void onPostExecute(Void parms) {
qrC.getQrActivity().showResult("Music Done.");
}
Thanks for your help!
You need to wait until the file is played.
Because the MediaPlayer mediaPlayer is created as local variable it will be release at the end of
protected Void doInBackground {
You have two options.
1) Make the mediaPlayer variable of class that live long enough
2) OR, put a loop reading mediaPlayer.status. Something like this:
while (mediaPlayer.status==MediaPlayer.Status.PLAYING)
sleep(100);

How to do streaming with .pls files in android?

I want to play a .pls file for my android application using this url http://playerservices.streamtheworld.com/pls/VIRGINRADIO_DUBAIAAC.pls
I know that it is not possible to play .pls files using MediaPlayer directly.So I parsed this file using a Pls parser and set each url to a media player.But it won't work .Also shows the error error (1, -2147483648).
public class PlayListParser {
private BufferedReader reader;
public PlayListParser(String url) {
try {
URL plsFileUrl = new URL(url.trim());
URLConnection urlConnection = plsFileUrl.openConnection();
// InputStream input = new BufferedInputStream(urlConnection.openStream());
InputStream iStream = urlConnection.getInputStream();
this.reader = new BufferedReader(new InputStreamReader(iStream));
// this.reader = new BufferedReader(new FileReader(file), 1024);
} catch (MalformedURLException e) {
Log.e("PlayListParser", "Got MalformedURLException = " + e.getMessage());
} catch (IOException e) {
Log.e("PlayListParser", "Got IOException = " + e.getMessage());
}
}
public List<String> getUrls() {
LinkedList<String> urls = new LinkedList<String>();
while (true) {
try {
String line = reader.readLine();
if (line == null) {
break;
}
String url = parseLine(line);
if (url != null && !url.equals("")) {
urls.add(url);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return urls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
}
PlayListParser playListParser = new PlayListParser(URL_PLS_STREAMING);
List<String > playList = playListParser.getUrls();
if(playList != null && ! playList.isEmpty()){
for(String url : playList){
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(playList.get(0));//"http://stream2.streamq.net:8020/");
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
//mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
Log.e("MainActivity","Got IllegalArgumentException = " + e.getMessage());
} catch (IllegalStateException e) {
Log.e("MainActivity","Got IllegalStateException = " + e.getMessage());
} catch (IOException e) {
Log.e("MainActivity","Got IOException = " + e.getMessage());
}
}
}
How can i play this .pls file? I could not find a good reference about it.Also i want to play,pause,and rewind these files.
Thanks in Advance
Get URL from .pls file
This will return URL like http://stream2.streamq.net:8020
package com.direct.radio.global;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import android.content.Context;
import android.util.Log;
public class GetStreamingUrl {
private static String LOGTAG = "GetStreamingUrl";
private Context mContext;
public GetStreamingUrl(Context context) {
Log.i(LOGTAG, "call to constructor");
this.mContext = context;
}
public LinkedList<String> getStreamingUrl(String url) {
Log.i(LOGTAG, "get streaming url");
final BufferedReader br;
String murl = null;
LinkedList<String> murls = null;
try {
URLConnection mUrl = new URL(url).openConnection();
br = new BufferedReader(
new InputStreamReader(mUrl.getInputStream()));
murls = new LinkedList<String>();
while (true) {
try {
String line = br.readLine();
if (line == null) {
break;
}
murl = parseLine(line);
if (murl != null && !murl.equals("")) {
murls.add(murl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(LOGTAG, "url to stream :" + murl);
return murls;
}
private String parseLine(String line) {
if (line == null) {
return null;
}
String trimmed = line.trim();
if (trimmed.indexOf("http") >= 0) {
return trimmed.substring(trimmed.indexOf("http"));
}
return "";
}
}
Activity_Player.java or Service_Player.java
you can write this code as per your need , Define this method
LinkedList<String> urls;
private LinkedList<String> fGetPlayableUrl(String mPls) {
GetStreamingUrl oGetStreamingUrl = new GetStreamingUrl(Activity_Splash.this);
urls = oGetStreamingUrl.getStreamingUrl(mPls);
return urls;
}
Here, fGetPlayableUrl(String mPls) pass .pls URL. Now you have streaming URL.
MediaPlayer mMediaPlayer = new MediaPlayer();
Now, pass URL to
mMediaPlayer.setDataSource(urls.toString());
mMediaPlayer.prepareAsync();
mMediaPlayer.start();

Categories

Resources