Unable to get output from Pd library and Android app - android

I am trying to get a simple Android app working with the Pd library I have integrated within my eclipse environment.
I have successfully build and compiled an example project called "CircleOfFifths" which proves that the library has been integrated fine in eclipse.
I am using cordova/phonegap and trying to create a plugin for libpd. All the plugin communication with the javascript file on the front-end is working fine.
The code seems to initialise and load the patch fine. It also goes into the play() method but I don't get any output. I am expecting to hear the sine wave.
I followed this tutorial on YouTube.
My code can be viewed here, and the patch is here.
Can anyone help me figure out where I can be going wrong?
My ultimate objective is to use a live audio from microphone and process that audio and return immediately with applied Pd patch (patch is ready and created for this) but before I go to that stage I want to make sure that I get some sort of output from the existing patch. Same patch as the one above in the YouTube tutorial.
package com.test.libpd;
import java.io.File;
import java.io.IOException;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.puredata.android.io.AudioParameters;
import org.puredata.android.io.PdAudio;
import org.puredata.android.utils.PdUiDispatcher;
import org.puredata.core.PdBase;
import org.puredata.core.utils.IoUtils;
import android.content.Context;
import android.util.Log;
import com.sgil.libpddemo.R;
public class Libpd extends CordovaPlugin {
private static final String TAG = "libpd_plugin";
private Exception exception;
private Context AppContext;
private PdUiDispatcher dispatcher;
private static final int MIN_SAMPLE_RATE = 44100;
public Libpd() { // constructor
}
private Context getApplicationContext() {
return this.cordova.getActivity().getApplicationContext();
}
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Log.v(TAG, "Init LIBPD PLUGIN");
}
public boolean execute(final String action, final JSONArray args,
final CallbackContext callbackContext) throws JSONException {
cordova.getActivity().runOnUiThread(new Runnable() {
// #SuppressLint("NewApi")
public void run() {
Log.v(TAG, "Plugin received:" + action);
Libpd libpd = new Libpd();
libpd.AppContext = getApplicationContext();
try {
libpd.initPd(libpd.AppContext);
libpd.loadPatch(libpd.AppContext);
} catch (IOException e) {
Log.e(TAG, e.toString());
// libpd.finish();
}
if (action.equals("playRec")) {
// MediaRecordMethod mediaRecordMethod = new
// MediaRecordMethod(action);
// mediaRecordMethod.init();
libpd.play();
}
if (action.equals("stopRec")) {
libpd.onPause();
}
if (action.equals("startRec")) {
libpd.record("start");
libpd.play();
}
}
});
return true;
}
private void initPd(Context ctx) throws IOException {
AudioParameters.init(ctx);
// Configure the audio glue
int sampleRate = AudioParameters.suggestSampleRate();
int srate = Math.max(MIN_SAMPLE_RATE, AudioParameters.suggestSampleRate());
// int sampleRate = 64;
int inpch = AudioParameters.suggestInputChannels();
int outpch = AudioParameters.suggestOutputChannels();
PdAudio.initAudio(srate, 0, outpch, 8, true);
// Create and install the dispatcher
dispatcher = new PdUiDispatcher();
PdBase.setReceiver(dispatcher);
}
private void loadPatch(Context ctx) throws IOException {
File dir = ctx.getFilesDir();
Log.v(TAG, "path:" + dir.getAbsolutePath().toString());
//File dir = new File("/sdcard/mypatches");
IoUtils.extractZipResource(
ctx.getResources().openRawResource(R.raw.simplepatch), dir, true);
File patchFile = new File(dir, "simplepatch.pd");
PdBase.openPatch(patchFile.getAbsolutePath());
//PdAudio.startAudio(ctx);
//this.record("start");
}
private void record(String startorStop) {
if (startorStop.equals("start")) {
PdBase.sendSymbol("recordfilename", "x.aiff");
PdBase.sendBang("openfile");
PdBase.sendBang("record");
} else {
PdBase.sendBang("stoprecording");
}
}
// play back the last recording from the file called 'recorded'
public void play() {
//PdBase.sendSymbol("playfilename", "x.aiff");
//PdBase.sendBang("readfile");
//PdBase.sendBang("play");
Float val = 1.0f;
PdBase.sendFloat("onOff", val);
}
protected void onPause() {
PdAudio.stopAudio();
PdAudio.release();
PdBase.release();
}
}

your code never starts the audio-processing.
For whatever reasons youhave uncommented the line
PdAudio.startAudio(ctx)

Related

Using OpenNLP with Android?

I would like to use OpenNLP in my Android project. I imported the JAR and I can use it in my project but when I need to load a TokenizerModel (for example) I do not see how to proceed.
Cheers.
Putting my .bin model files in the assets folder and call the using getAssets() is working pretty fine.
Here is an example (originally written on Stack Overflow Documentation):
Sentence Detection using openNLP using CLI and Java API
using CLI:
$ opennlp SentenceDetector ./en-sent.bin < ./input.txt > output.txt
using API:
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.Objects;
public class FileUtils {
/**
* Get file data as string
*
* #param fileName
* #return
*/
public static String getFileDataAsString(String fileName) {
Objects.nonNull(fileName);
try {
String data = new String(readAllBytes(get(fileName)));
return data;
} catch (IOException e) {
System.out.println(e.getMessage());
return null;
}
}
}
class sentecedetectorutil:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
public class SentenceDetectorUtil {
private SentenceModel model = null;
SentenceDetectorME sentenceDetector = null;
public SentenceDetectorUtil(String modelFile) {
Objects.nonNull(modelFile);
initSentenceModel(modelFile);
initSentenceDetectorME();
}
private void initSentenceDetectorME() {
sentenceDetector = new SentenceDetectorME(model);
}
private SentenceModel initSentenceModel(String file) {
InputStream modelIn;
try {
modelIn = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return null;
}
try {
model = new SentenceModel(modelIn);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (modelIn != null) {
try {
modelIn.close();
} catch (IOException e) {
}
}
}
return model;
}
public String[] getSentencesFromFile(String inputFile) {
String data = FileUtils.getFileDataAsString(inputFile);
return sentenceDetector.sentDetect(data);
}
public String[] getSentences(String data) {
return sentenceDetector.sentDetect(data);
}
}
}
main class:
public class Main {
public static void main(String args[]) {
SentenceDetectorUtil util = new SentenceDetectorUtil(
"path//to//your//en-sent.bin");
String data = "Welcome to Stackoverflow Documentation.This is the first example in OenNLP.";
String[] sentences = util.getSentences(data);
for (String s : sentences)
System.out.println(s +"\n");
}
}
output will be:
Welcome to Stackoverflow Documentation.
This is the first example in OpenNLP.
And you can find some basic stuff here
lot of examples are covered in the above examples. that must do the work for you.

Cannot resolve myAPI. Is it an external library?

I am new to android programming language. I am referring to the link , But failing to understand what MyAPI is in this piece of code. I found a similar question on stack overflow. However, I cannot even resolve this MyAPI library, and he could find it initially which later stopped working. Where can I find it?
import android.content.Context;
import android.os.AsyncTask;
import android.util.Pair;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import java.io.IOException;
class SendRegisterInfo extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
#Override
protected String doInBackground(Pair<Context, String>... params) {
if(myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?>
abstractGoogleClientRequest)
throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
You can find MyApi.java in the backend.
#Google Cloud Endpoints

Muzei database doesn't update when I update external JSON

I'm in the middle of making a wallpaper app for android and I'm have a problem with Muzei support and hoping someone here can help me see what I'm missing.
I have a JSON file which my app uses to get the wallpaper URLs and display the pictures from. It works fine and it gets the right images. However if I update the JSON with more entries and more images then the Muzei extension still uses the old database. I was thinking that maybe it caches the database and just doesn't update it for whatever reason. The only way to get it to use the updated JSON file is to clear the data of my app and set a different extension in Muzei and the reset Muzei with my extension. Which would not be very user friendly.
Probably just being blind but help would be appreciated.
ArtSource.java:
package com.main.walls.muzei;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.google.android.apps.muzei.api.Artwork;
import com.google.android.apps.muzei.api.RemoteMuzeiArtSource;
import com.google.android.apps.muzei.api.UserCommand;
import com.main.walls.utilities.Preferences;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Random;
import walls.wallpaper.R;
public class ArtSource extends RemoteMuzeiArtSource {
private WallsDatabase wdb;
private ArrayList<WallpaperInfo> wallslist;
private Preferences mPrefs;
private static final String ARTSOURCE_NAME = "Walls";
private static final String JSON_URL = "http://pastebin.com/raw.php?i=VWTzhJ0N";
private static final String MARKET_URL = "https://play.google.com/store/apps/details?id=";
private static final int COMMAND_ID_SHARE = 1337;
public ArtSource() {
super(ARTSOURCE_NAME);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String command = intent.getExtras().getString("service");
if (command != null) {
try {
onTryUpdate(UPDATE_REASON_USER_NEXT);
} catch (RetryException e) {
Log.d("MuzeiArtSource", Log.getStackTraceString(e));
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
wdb = new WallsDatabase(getApplicationContext());
wallslist = new ArrayList<>();
mPrefs = new Preferences(ArtSource.this);
ArrayList<UserCommand> commands = new ArrayList<>();
commands.add(new UserCommand(BUILTIN_COMMAND_ID_NEXT_ARTWORK));
commands.add(new UserCommand(COMMAND_ID_SHARE, getString(R.string.justshare)));
setUserCommands(commands);
}
#Override
public void onCustomCommand(int id) {
super.onCustomCommand(id);
if (id == COMMAND_ID_SHARE) {
Artwork currentArtwork = getCurrentArtwork();
Intent shareWall = new Intent(Intent.ACTION_SEND);
shareWall.setType("text/plain");
String authorName = currentArtwork.getByline();
String storeUrl = MARKET_URL + getResources().getString(R.string.package_name);
String iconPackName = getString(R.string.app_name);
shareWall.putExtra(Intent.EXTRA_TEXT,
getString(R.string.partone) + authorName +
getString(R.string.parttwo) + iconPackName +
getString(R.string.partthree) + storeUrl);
shareWall = Intent.createChooser(shareWall, getString(R.string.share_title));
shareWall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(shareWall);
}
}
#Override
protected void onTryUpdate(int reason) throws RetryException {
if (mPrefs.isFeaturesEnabled()) {
if (wallslist.size() == 0)
getWallpapersFromUrl(JSON_URL);
int i = getRandomInt();
String token = wallslist.get(i).getWallURL();
publishArtwork(new Artwork.Builder()
.byline(wallslist.get(i).getWallAuthor())
.imageUri(Uri.parse(wallslist.get(i).getWallURL()))
.token(token)
.viewIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(wallslist.get(i).getWallURL())))
.build());
scheduleUpdate(System.currentTimeMillis() + mPrefs.getRotateTime());
}
}
private int getRandomInt() {
return new Random().nextInt(wallslist.size());
}
private void getWallpapersFromUrl(String url) {
wallslist.clear();
wallslist = wdb.getAllWalls();
if (wallslist.size() == 0) {
try {
HttpClient cl = new DefaultHttpClient();
HttpResponse response = cl.execute(new HttpGet(url));
if (response.getStatusLine().getStatusCode() == 200) {
final String data = EntityUtils.toString(response.getEntity());
JSONObject jsonobject = new JSONObject(data);
final JSONArray jsonarray = jsonobject.getJSONArray("wallpapers");
wallslist.clear();
wdb.deleteAllWallpapers();
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WallpaperInfo jsondata = new WallpaperInfo(
jsonobject.getString("author"),
jsonobject.getString("url")
);
wdb.addWallpaper(jsondata);
wallslist.add(jsondata);
}
}
} catch (Exception e) {
Log.d("Wallpapers", Log.getStackTraceString(e));
}
}
}
}
Not sure if I need any other code in here or not and the logcat doesn't say anything, it's as though it's it's working as normal. If you need to see more code just let me know.
Thanks for any help.
Basically I was right and I was just being stupid and missing the simplest thing, it didn't even have anything to do with ArtSource.java.
In WallsDatabase.Java I wasn't updating DATABASE_VERSION. I was leaving it at 1 and so when I updated the app it didn't bother to update the database because the version was the same.
So just change the value of private static final int DATABASE_VERSION = 1 to a higher number and it should work great.
Simple mistake but an easy one to make I guess.

DalvikVm could not found class android library project

Need to tap the collective brain power here. I am trying out a very simple BindService and communicate with Messenger example. Since I am passing message object in the Message.obj field I defined messages in their own Android library project to be shared between service and the client. I can compile fine by including the message library as a depdendency but during runtime dalvikvm complains it could not find class. I have read other related issue dealing with export and orders but same solution doesn't help in my case. It must be a very simple mistake but I am pulling my hair out right now.
App depends on SupportServiceMessageLibrary.
App has library before its src in project's order tab.
Lib is not checked for export in App since no one is consuming the App
Library is exporting its src and gen folder.
The error message from log cat:
01-31 01:53:41.134: E/dalvikvm(22886): Could not find class 'com.example.service.RequestStatus', referenced from method com.example.MainActivity$ServiceReplyHandler.handleMessage
Here are snippet of code
MainActivity
package com.example;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.Menu;
import android.widget.TextView;
import com.example.appserver.R;
import com.example.service.MessageType;
import com.example.service.RequestStatus;
public class MainActivity extends Activity {
private TextView serverStatus;
/** Messenger for sending message to service. */
Messenger mServiceMessenger = null;
/** Flag indicating whether we have called bind on the service. */
boolean mBound;
/** Messenger for receiving message from service */
Messenger mClientMessenger = null;
class ServiceReplyHandler extends Handler {
#Override
public void handleMessage(Message msg) {
if (msg.what == MessageType.MSG_REPLY) {
RequestStatus reqStatus = (RequestStatus) msg.obj;
}
}
}
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mServiceMessenger = new Messenger(service);
Message regMsg = Message.obtain(null,
MessageType.MSG_REGISTER);
regMsg.replyTo = mClientMessenger;
try {
mServiceMessenger.send(regMsg);
} catch (RemoteException e) {
}
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mServiceMessenger = null;
mBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
serverStatus = (TextView) findViewById(R.id.server_status);
Intent startServiceIntent = new Intent();
startServiceIntent.setComponent(new ComponentName(
"com.example.supportservices",
"com.example.service.EntitlementService"));
bindService(startServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
// Initialize messenger to receiver service messages;
mClientMessenger = new Messenger(new ServiceReplyHandler());
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.server, menu);
return true;
}
}
And the message itself
package com.example.service;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
public class RequestStatus {
public static int REQUEST_SUCCESS = 0;
public static int REQUEST_FAILURE = 1;
public static String TYPE = "request_status";
public static String STATUS_JSON_KEY = "status";
private int status;
public RequestStatus(int status) {
this.status = status;
}
public static RequestStatus fromJson(String json) {
try {
JSONObject msg = new JSONObject(json);
String type = msg.getString("type");
if (TextUtils.isEmpty(type) || TYPE.equals(type) == false) {
return null;
}
return(new RequestStatus(msg.getJSONObject("body").getInt(STATUS_JSON_KEY)));
} catch (JSONException e) {
return null;
}
}
public String toJson() {
JSONObject msg = new JSONObject();
try {
msg.put("type", TYPE);
JSONObject body = new JSONObject();
body.put(STATUS_JSON_KEY, status);
msg.put("body", body);
} catch (JSONException e) {
return null;
}
return msg.toString();
}
}
Go to project property of the App and add it as a library under Android in addition to project dependency under build path.

webserver for file upload on android

I would like to add a webserver to my android application for uploading small files to the phone.
The user would start the webserver from the phone by hitting a button. He would then see an ip address that can be accessed by any browser from a pc. The website behind this ip address should show a file upload opportunity.
My question is: Is there an open source project similar to my needs? Or how would you recommend doing this?
you can use NanoHttpd link it's very weight android web server that is nicely embbedible..
package .....;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class AndroidWebServerActivity extends Activity {
private static final int PORT = 8765;
private TextView hello;
private MyHTTPD server;
private Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume() {
super.onResume();
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT, null);
}
#Override
public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
final StringBuilder buf = new StringBuilder();
for (Entry<Object, Object> kv : header.entrySet())
buf.append(kv.getKey() + " : " + kv.getValue() + "\n");
handler.post(new Runnable() {
#Override
public void run() {
}
});
final String html = "<html><head><head><body><h1>Hello, World</h1></body></html>";
return new NanoHTTPD.Response(HTTP_OK, MIME_HTML, html);
}
}
}

Categories

Resources