How to do streaming with .pls files in android? - 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();

Related

Android java json url from dropbox

I have this piece of code on android that reads data from Assets folder, so I need from this code to read data from external like dropbox. Ho to change and read data from dropbox. thanks
#Override
protected RadioDatas doInBackground(Void... params) {
BufferedReader reader = null;
ArrayList<RadioData> radioDatas = new ArrayList<>();
RadioDatas datas = new RadioDatas();
try {
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("url.txt"), "Unicode"));
String mLine;
while ((mLine = reader.readLine()) != null) {
RadioData radioData = new RadioData();
String[] meta = mLine.split(";");
radioData.setUrl(meta[0]);
radioData.setTitle(meta[1]);
radioData.setGenres(meta[2]);
radioDatas.add(radioData);
}
} catch (IOException e) {
//log the exception
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
datas.setRadioDatas(radioDatas);
return datas;
}
This would work....
public class Execute extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler handler = new HttpHandler();
String jsonString = handler.makeServiceCall(json);
if (jsonString != null) {
try {
//parse jsonString
} catch (JSONException e) {
Log.i("Error with parsing", e.getMessage());
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
You will need a HTTPHandler class...
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
in.close();
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
To run it.
new Execute().execute;

Sending Variables to a REST api to be saved on server

I am really struggling with this for some time now and I am really lost in terms of how this works.
I have written a REST service in netbeans and I have passed through Json data and tested that it works using Postman and it is successfully saving to the database.
Now, I want the variables in my mobile application to be sent to that REST api so that they can then be saved to the database.
I have looked at many answers on this but can get none which fully explain to me how to do this.. Ideally I am trying to POST or PUT data from my mobile app into my database.
Here is what I have tried so far:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
details = editTextDetails.getText().toString();
getCurrentDateandTime();
String url = "http://localhost:8080/engAppApi/webservices/engineerTable/";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
JSONObject params = new JSONObject();
try {
params.put("machinetype", machineType);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("workordernumber", workOrderNumber);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("employeename", employee);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("activity", activity);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("durationhours", durationHours);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("durationmins", durationMins);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("downtimehours", downTimeHours);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("downtimemins", downTimeMins);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("currentdateandtime", currentDateandTime);
} catch (JSONException e) {
e.printStackTrace();
}
StringEntity jsonEntity = null;
try {
jsonEntity = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request = new HttpPost(url);
request.addHeader("Content-Type", "application/json");
request.setEntity(jsonEntity);
try {
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
can someone please point me in the right direction
Thanks in advance!
just use retrofit 2 for connect to server.
see this link
You have an idea in how to do the post petition, but you have a couple of problems. The first and more important problem is that if you want to retrieve information from a server, you must put your code in an async task. You can't do it in UI Thread. So, i'm gonna share with you a class that implements all the logic you need and you just have to use it. First you need to use gson, look how to use it here
https://github.com/google/gson
and the code is here. It have two methods, one for GET and other for POST.
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Administrador on 4/27/2017.
*/
public class JsonReaderFromUrl {
public static final int SUCCESS = 0;
public static final int FAILED = 1;
public static final int PROGRESS = 2;
public interface OnJesonInterface{
void OnJsonReceive(int status, JSONObject jsonObject, int key);
}
public JsonReaderFromUrl() {
}
public void getJsonFromUrlPost(final String url, final OnJesonInterface onJesonInterface, final String body, final int key){
new AsyncTask<Void, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
onJesonInterface.OnJsonReceive(PROGRESS,null,0);
}
#Override
protected String doInBackground(Void... params) {
if(android.os.Debug.isDebuggerConnected())
android.os.Debug.waitForDebugger();
try {
URL urlJson = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
connection.setDoInput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(body);
writer.flush();
writer.close();
outputStream.close();
connection.connect();
StringBuilder stringBuilder = new StringBuilder();
int httpStatus = connection.getResponseCode();
if (httpStatus == HttpURLConnection.HTTP_CREATED){
BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(),"utf-8")
);
String line = "";
while ((line = br.readLine()) != null){
stringBuilder.append(line + "\n");
}
br.close();
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null){
try {
JSONObject jsonObject = new JSONObject(s);
onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,key);
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
onJesonInterface.OnJsonReceive(FAILED,null,0);
}
}
}.execute();
}
public void getJsonFromUrl(final String url, final OnJesonInterface onJesonInterface){
AsyncTask<Void,String,String> asyncTask = new AsyncTask<Void, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
onJesonInterface.OnJsonReceive(PROGRESS,null,0);
}
#Override
protected String doInBackground(Void... params) {
try {
URL urlJson = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null){
stringBuffer.append(line + "\n");
Log.d("RESPONDE JSON: ",">" + line);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null){
try {
JSONObject jsonObject = new JSONObject(s);
onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,0);
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
onJesonInterface.OnJsonReceive(FAILED,null,0);
}
}
}.execute();
}
}
import this class where you need and use it PD: The key value is an int that can be used to retrieve what response correspond to each petition, this in case you use this class with a lot of petitions.

Async task on Android using web services

So I have this app I'm trying to make. I just want a photo of a place from a ID of the place that I get from an intent of the previous Activity, and I wanted to know how can I change my code in order to so with an async task.
Here is the Activity code:
public class CrearViajeActivity2 extends AppCompatActivity {
private String TAG="URL ERROR >>> : ";
private Intent intent;
private String Placeid, imageURL ,reference;
private final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private ImageView PlaceImage;
URLService service;
private ArrayList<String> photosR;
public CrearViajeActivity2() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crear_viaje2);
intent = getIntent();
Placeid = intent.getStringExtra("PlaceID");
PlaceImage = findViewById(R.id.imageView2);
// THIS IS WHAT I HAVE TO FIX , WITH AN ASYNC TASK OR SOMETHING , IF I COMMENT THIS 2 LINES THE APP THROWS AN EXCEPTION AND STOPS WORKING BUT I DONT KNOW HOW TO IMPLEMENT IT(DO IT) .
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//HERE I GET THE REFERENCE OF THE PLACE
reference=String.format("https://maps.googleapis.com/maps/api/place/details/json?placeid=%s&key=%s",Placeid,API_KEY);
service= new URLService();
String jsonStr = service.URLService(reference);
photosR = new ArrayList<>();
if(jsonStr!=null){
try{
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonObjResult = jsonObj.getJSONObject("result");
JSONArray photos = jsonObjResult.getJSONArray("photos");
for (int i = 0; i < photos.length(); i++) {
JSONObject c = photos.getJSONObject(i);
String photoReference = c.getString("photo_reference");
photosR.add(photoReference);
}
}catch(JSONException ex){
Log.e(TAG, "JSON FAILED: " + ex.getMessage());
Toast.makeText(getApplicationContext(),
"JSON FAILED: " + ex.getMessage(),
Toast.LENGTH_LONG)
.show();
}
}else{
Log.e(TAG, "JSON FAILED.");
}
// AND HERE I FINALLY GET THE PHOTO
imageURL =String.format("https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=%s&key=%s",photosR.get(0),API_KEY);
try{
URL url = new URL(imageURL);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
PlaceImage.setImageBitmap(bmp);
}catch(MalformedURLException ex){
}catch(IOException ex){
}
}
}
Here is the service class:
private static final String TAG = URLService.class.getSimpleName() +" >> : ";
public URLService() {
}
private String convertirStreamaString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String URLService(String reqUrl) {
String ref = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// READS THE REFERENCE OF THE PHOTO
InputStream in = new BufferedInputStream(conn.getInputStream());
ref = convertirStreamaString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return ref;
}
}

failed to connect to http Android

when the connection is so low i get an exception " failed to connect to : http ......", this is my code, can any one please helps me to avoid the exception.
when the connection is so low i get an exception " failed to connect to : http ......", this is my code, can any one please helps me to avoid the exception
private void parseM3uUrlAndPrepare_new(final String url) {
AsyncTask<String, Integer, String> asyn = new AsyncTask<String, Integer, String>(){
URL the_url;
HttpURLConnection conn;
String filePath = "";
InputStream inputStream;
HttpGet getRequest;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
the_url = new URL(url);
conn = (HttpURLConnection) the_url.openConnection(Proxy.NO_PROXY);
getRequest = new HttpGet(url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
if(conn != null) {
try {
inputStream = new BufferedInputStream(conn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("#")) {
}
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){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return filePath;
}
#Override
protected void onPostExecute(String filePath) {
try {
mediaPlayer.setDataSource(filePath);
DATA_SET = true;
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("");
}
Maybe the problem is the BufferedInputStream. I wrote this code (a long time ago) if you want to try it.
Give an input stream to the fonction and let it work.
import java.io.InputStream;
import java.util.Scanner;
/**
* Created by badetitou.
*/
public class ReadIt {
public static String ReadIt(InputStream is){
return new Scanner(is,"UTF-8").useDelimiter("").next();
}
}

How to play .pls in 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.

Categories

Resources