Using YouTube Data Api in Android - android

Am trying to use YouTube Data Api in my android app. When i try to run it as a java project, it runs fine without any errors. But when i try to do the same thing in my android application , the application force closes. Here is the output from logcat and my code.
OUTPUT FROM LOGCAT
01-05 00:13:17.198: E/AndroidRuntime(627): FATAL EXCEPTION: main
01-05 00:13:17.198: E/AndroidRuntime(627): java.lang.ExceptionInInitializerError
01-05 00:13:17.198: E/AndroidRuntime(627): at com.example.allinonedata.YouTubeManager.retrieveVideos(YouTubeManager.java:29)
...
01-05 00:13:17.198: E/AndroidRuntime(627): Caused by: java.lang.NoClassDefFoundError: com.google.gdata.data.media.MediaSource
HERE IS THE CODE
mainactivity.java
package com.example.allinonedata;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
String clientID = "JavaCodeGeeks";
String textQuery = "nexus 4";
int maxResults = 1;
boolean filter = true;
int timeout = 2000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubeManager ym = new YouTubeManager(clientID);
try{
List<YouTubeVideo> videos = ym.retrieveVideos(textQuery, maxResults, filter, timeout);
for (YouTubeVideo youtubeVideo : videos) {
System.out.println(youtubeVideo.getWebPlayerUrl());
System.out.println("Thumbnails");
for (String thumbnail : youtubeVideo.getThumbnails()) {
System.out.println("\t" + thumbnail);
}
System.out.println(youtubeVideo.getEmbeddedWebPlayerUrl());
System.out.println("**************************************************");
}
}
catch(Exception e)
{
}
}
}
youtubemanager.java
package com.example.allinonedata;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.media.mediarss.MediaThumbnail;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeMediaContent;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
public class YouTubeManager {
private static final String YOUTUBE_URL = "http://gdata.youtube.com/feeds/api/videos";
private static final String YOUTUBE_EMBEDDED_URL = "http://www.youtube.com/v/";
private String clientID;
public YouTubeManager(String clientID) {
this.clientID = clientID;
}
public List<YouTubeVideo> retrieveVideos(String textQuery, int maxResults,
boolean filter, int timeout) throws Exception {
YouTubeService service = new YouTubeService(clientID);
service.setConnectTimeout(timeout); // millis
YouTubeQuery query = new YouTubeQuery(new URL(YOUTUBE_URL));
query.setOrderBy(YouTubeQuery.OrderBy.RELEVANCE);
query.setFullTextQuery(textQuery);
query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);
query.setMaxResults(maxResults);
VideoFeed videoFeed = service.query(query, VideoFeed.class);
List<VideoEntry> videos = videoFeed.getEntries();
return convertVideos(videos);
}
private List<YouTubeVideo> convertVideos(List<VideoEntry> videos) {
List<YouTubeVideo> youtubeVideosList = new LinkedList<YouTubeVideo>();
for (VideoEntry videoEntry : videos) {
YouTubeVideo ytv = new YouTubeVideo();
YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
String webPlayerUrl = mediaGroup.getPlayer().getUrl();
ytv.setWebPlayerUrl(webPlayerUrl);
String query = "?v=";
int index = webPlayerUrl.indexOf(query);
String embeddedWebPlayerUrl = webPlayerUrl.substring(index+query.length());
embeddedWebPlayerUrl = YOUTUBE_EMBEDDED_URL + embeddedWebPlayerUrl;
ytv.setEmbeddedWebPlayerUrl(embeddedWebPlayerUrl);
List<String> thumbnails = new LinkedList<String>();
for (MediaThumbnail mediaThumbnail : mediaGroup.getThumbnails()) {
thumbnails.add(mediaThumbnail.getUrl());
}
ytv.setThumbnails(thumbnails);
List<YouTubeMedia> medias = new LinkedList<YouTubeMedia>();
for (YouTubeMediaContent mediaContent : mediaGroup.getYouTubeContents()) {
medias.add(new YouTubeMedia(mediaContent.getUrl(), mediaContent.getType()));
}
ytv.setMedias(medias);
youtubeVideosList.add(ytv);
}
return youtubeVideosList;
}
}

The google-api-java-client (which does have Android support, unlike the gdata-client) didn't previously support the Youtube Data API, but with the release of v3 this is now rectified; there is good Youtube support now with this client that should provide you what you need. See here for details and code samples:
https://developers.google.com/api-client-library/java/apis/youtube/v3
and also to Getting started Guide here
https://developers.google.com/youtube/v3/getting-started

Related

Calling api.ai from Android

I am building an android app in which I am calling api.ai. I want to parse the response and display it to users. Earlier I had written code in node.js which is as below:
function sendMessageToApiAi(options,botcontext) {
var message = options.message; // Mandatory
var sessionId = options.sessionId || ""; // optinal
var callback = options.callback;
if (!(callback && typeof callback == 'function')) {
return botcontext.sendResponse("ERROR : type of options.callback should be function and its Mandatory");
}
var nlpToken = options.nlpToken;
if (!nlpToken) {
if (!botcontext.simpledb.botleveldata.config || !botcontext.simpledb.botleveldata.config.nlpToken) {
return botcontext.sendResponse("ERROR : token not set. Please set Api.ai Token to options.nlpToken or context.simpledb.botleveldata.config.nlpToken");
} else {
nlpToken = botcontext.simpledb.botleveldata.config.nlpToken;
}
}
var query = '?v=20150910&query='+ encodeURIComponent(message) +'&sessionId='+context.simpledb.roomleveldata.c1+'&timezone=Asia/Calcutta&lang=en '
var apiurl = "https://api.api.ai/api/query"+query;
var headers = { "Authorization": "Bearer " + nlpToken};
botcontext.simplehttp.makeGet(apiurl, headers, function(context, event) {
if (event.getresp) {
callback(event.getresp);
} else {
callback({})
}
});
}
My Android code is as below:
package com.example.pramod.apidev;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity{
private Button listenButton;
private TextView resultTextView;
private EditText inputText;
private static String API_URL = "https://api.api.ai/api/query";
private static String API_KEY = "d05b02dfe52f4b5f969ba1257cffac37";
private static String query;
private static String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listenButton = (Button) findViewById(R.id.listenButton);
resultTextView = (TextView) findViewById(R.id.resultTextView);
inputText = (EditText)findViewById(R.id.inputText);
s = inputText.getText().toString();
query = "?v=20150910&query=hi" +"&sessionId=1480181847573api&timezone=Asia/Calcutta&lang=en";
listenButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
URL url = new URL(API_URL + query + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
}
}
});
}
}
I need help in following:
(i) How can call the Api.ai since I am getting an error 401? Can some one tell how to exactly call Api.ai using the Node.js code?
(ii) How can parse the response and display it to users?
Thanks in advance
I'm connecting with api.ai from android app.
The steps to do are the following
1. Add the dependencies:
compile 'ai.api:libai:1.2.2'
compile 'ai.api:sdk:2.0.1#aar'
2. Create an activity implementing AIListener.
3. Declare AIService,and AIDataService:
private AIService aiService;
private AIDataService aiDataService;
4. Initialize config, services and add listener:
final ai.api.android.AIConfiguration config = new ai.api.android.AIConfiguration("API_KEY",
ai.api.android.AIConfiguration.SupportedLanguages.Spanish,
ai.api.android.AIConfiguration.RecognitionEngine.System);
// Use with text search
aiDataService = new AIDataService(this, config);
// Use with Voice input
aiService = AIService.getService(this, config);
aiService.setListener(this);
5. Execute async task to make request:
AIRequest aiRequest = new AIRequest();
aiRequest.setQuery(request);
//request--any string you want to send to chat bot to get there corresponding response.
if(aiRequest==null) {
throw new IllegalArgumentException("aiRequest must be not null");
}
final AsyncTask<AIRequest, Integer, AIResponse> task =
new AsyncTask<AIRequest, Integer, AIResponse>() {
private AIError aiError;
#Override
protected AIResponse doInBackground(final AIRequest... params) {
final AIRequest request = params[0];
try {
final AIResponse response = aiDataService.request(request);
// Return response
return response;
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
};
task.execute(aiRequest);
6. onResult method
Result result = response.getResult();
If the result is a string, the string with the response will be in:
String speech = result.getFulfillment().getSpeech();
Regards.
Nuria
You can refer the official documentation of integrating API.AI here -
https://github.com/api-ai/apiai-android-client
Happy coding.

Bluemix: How to insert JSON in Cloudant in Android with Replicator?

I am finding it difficult to make this simple upload. I've used all encontrandos tutorials on the internet such as Bluelist and android-sync. I already have a database created within the service. My code is as follows:
MainActivity.java
package com.example.engenharia.replicator;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreException;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.query.IndexManager;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class MainActivity extends AppCompatActivity {
private static final String DATASTORE_MANGER_DIR = "data";
private Datastore DataStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URI uri = new URI(my_uri);
File path = getApplicationContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
DataStore = manager.openDatastore("banco0"); //banco0 is the DB created in Cloudant NoSQL service.
// Create a replicator that replicates changes from the local
// datastore to the remote database.
Replicator replicator = ReplicatorBuilder.push().to(uri).from(DataStore).build();
// Use a CountDownLatch to provide a lightweight way to wait for completion
CountDownLatch latch = new CountDownLatch(1);
Listener listener = new Listener(latch);
replicator.getEventBus().register(listener);
replicator.start();
latch.await();
replicator.getEventBus().unregister(listener);
if(replicator.getState() != Replicator.State.COMPLETE){
System.out.println("Error replicating TO remote");
System.out.println(listener.error);
} else {
System.out.println(String.format("Replicated %d documents in %d batches",
listener.documentsReplicated, listener.batchesReplicated));
}
}catch (Exception e){
e.printStackTrace();
}
}
public DocumentRevision createDocument() {
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.body = DocumentBodyFactory.create(HashMap());
try {
return DataStore.createDocumentFromRevision(rev);
} catch (DocumentException e) {
//throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
public Map<String, Object> HashMap() {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Street", "121");
map1.put("Street1", "12112");
map1.put("Street123", "1211111");
String[] array1 = new String[]{"Cloudant", "NoSQL", "JSON"};
map.put("address", map1);
map.put("description", "This is sample description");
map.put("skills", array1);
return map;
}
}
listener.java
package com.example.engenharia.replicator;
import com.cloudant.sync.notifications.ReplicationCompleted;
import com.cloudant.sync.notifications.ReplicationErrored;
import com.cloudant.sync.replication.ErrorInfo;
import com.google.common.eventbus.Subscribe;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.util.concurrent.CountDownLatch;
/**
* Created by engenharia on 19/08/16.
*/
public class Listener {
private final CountDownLatch latch;
public ErrorInfo error = null;
public int documentsReplicated;
public int batchesReplicated;
Listener(CountDownLatch latch) {
this.latch = latch;
}
#Subscribe
public void complete(ReplicationCompleted event) {
this.documentsReplicated = event.documentsReplicated;
this.batchesReplicated = event.batchesReplicated;
latch.countDown();
}
#Subscribe
public void error(ReplicationErrored event) {
this.error = event.errorInfo;
latch.countDown();
}
}
Executing this code I have the follow error:
CouchException: error: forbidden, reason: server_admin access is
required for this request, statusCode: 403, msg: null, cause: null
But I am the admin!
How do I fix the problem or what is the solution?

There was a service error: 403 in android

I am making youtube search video through my app. For this I have create a project on google developer console and provide credentials like package name and SHA - 1 certificate and get YouTubeApi key that is use in my project but when i run program it throw GoogleJsonResponseException exception with some message. I am not understanding what is that exception and how can we resolve it.
below is exception
05-07 15:26:23.858 12602-12738/com.dp.videostoreadmin W/System.err: There was a service error: 403 : The Android package name and signing-certificate fingerprint, null and null, do not match the app restrictions configured on your API key. Please use the API Console to update your key restrictions.
below is my activity code
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.IOException;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String YOUTUBE_API_KEY = "AIzaSyDielPMOnvIiOh5Rh3MyPRfFTprFmcX0Cw";
EditText searchText;
Button submit;
private static YouTube youtube;
private static final long NUMBER_OF_VIDEOS_RETURNED = 25;
String queryKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchText = (EditText) findViewById(R.id.editText);
submit = (Button) findViewById(R.id.submit);
queryKey = searchText.getText().toString();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new getSearchResult().execute();
}
});
}
public class getSearchResult extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params) {
try {
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("VideoStoreAdmin").build();
YouTube.Search.List search = youtube.search().list("id,snippet");
search.setKey(YOUTUBE_API_KEY);
search.setQ(queryKey);
search.setType("video");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/publishedAt,snippet/thumbnails/default/url),nextPageToken");
search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
// Call the API and print results.
SearchListResponse searchResponse = search.execute();
List<SearchResult> searchResultList = searchResponse.getItems();
if (searchResultList != null) {
Log.d("TAG",searchResultList.toString());
}
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}
}

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.

Unable to get output from Pd library and Android app

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)

Categories

Resources