Using external libraries when developing Android application - java

I want to implement an application that uses image recognition system IQEngines. I'm using eclipse for that. I'm trying test codes IQEngines provide but the result I'm getting is that "File apple.jpg does't exist"
I'm not sure where the problem lies. It seems like I imported all relevant jar files so the code should work. In eclipse I changed Main method into onCreate so that the activity can run
Does anyone have a clue?? Has anyone ever used IQEngines?
There's javaiqe.java that javaiqe_test.java is using but it's very long so I don't want to attach
package com.Camera;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.iqengines.javaiqe.javaiqe;
import com.iqengines.javaiqe.javaiqe.IQEQuery;
/**
* IQEngines Java API
*
* test file
*
* #author
*/
public class javaiqe_test extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.resultImg);
final String KEY = "64bc6a7fd77643899d3af8b305924165";
final String SECRET = "c27e162ea7c24c619f850014124598";
/*
* An API object is initialized using the API key and secret
*/
iqe = new javaiqe(KEY, SECRET);
uploadObject();
/*
* You can quickly query an image and retrieve results by doing:
*/
File test_file = new File("apple.jpg");
// Query
IQEQuery query = iqe.query(test_file);
System.out.println("query.result : " + query.getResult());
System.out.println("query.qid : " + query.getQID());
tv.setText(query.getResult());
// Update
/* String update = iqe.update();
System.out.println("Update : " + update);*/
// Result
String result = iqe.result(query.getQID(), true);
System.out.println("Result : " + result);
// Upload
//uploadObject();
}
/**
* Sample code for uploading an object
*/
public static void uploadObject() {
// Your object images
ArrayList<File> images = new ArrayList();
images.add(new File("res/drawable/apple.jpg"));
// Object infos
String name = "Computational Geometry, Algorithms and Applications, Third Edition";
// Optional infos
String custom_id = "book0001";
String meta = "{\n\"isbn\": \"9783540779735\"\n}";
boolean json = false;
String collection = "books";
// Upload
//System.out.println("Upload : " + iqe.upload(images, name, custom_id, meta, json, collection));
System.out.println("Upload : " + iqe.upload(images, name));
}
private static javaiqe iqe = null;
}

If you're sure you've imported everything you need, then it could be useful, if you clean your eclipse project, and rebuild it again. Other reason might be - that you've forgotten to 'redeploy' your application.
This might be helpful too.
Good luck! Probably you've missed some minor detail - I've been using external jars without any problems in Android projects.

Related

How to write to files in android studio? Where are the files stored?

How would I be able to create a new file which will have a different file name each time? Would it also be possible to add line breaks when writing to these files? Also, how would I be able to access this file?
package com.example.create_recipe;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
EditText editTxtRecipeName, editTxtEquipment, editTxtIngredients, editTxtMethod, editPersonalStory;
Spinner spnCountries, spnHours, spnMinutes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createRecipe(Context context) throws FileNotFoundException {
//TODO Create new file - should it be named after the recipe name or a unique int id?
String recipeName = editTxtRecipeName.getText().toString();
String country = spnCountries.getSelectedItem().toString();
String hours = spnHours.getSelectedItem().toString();
String minutes = spnMinutes.getSelectedItem().toString();
String equipment = editTxtEquipment.getText().toString();
String ingredients = editTxtIngredients.getText().toString();
String method = editTxtMethod.getText().toString();
String personalStory = editPersonalStory.getText().toString();
//TODO Write to file, adding new line breaks between recipeName, equipment and so on.
}
}
WHat you need is an UUID and use it like so
val uuid = UUID.randomUUID().toString()
val path = Environment.getExternalStorageDirectory().path + "/" + FILE_NAME
val file = File(path)
BufferedOutputStream(FileOutputStream(file.path)).use { stream ->
stream.write(uuid.toByteArray())
}
Please noteEnvironment.getExternalStorageDirectory() will not work post API 29. This example is just meant to show the use of UUID to generate unique values to store
Getting your app directory (ContextWrapper is an Application/Activity/Service):
String dir = ContextWrapper#getFilesDir().getAbsolutePath();
Obtaining the complete file path:
String path = dir + "/" + fileName + ".anything";
Obtaining a file-object:
File file = new File(path);
Saving a byte array:
Files.write(dir, content);
Or a file:
FileWriter writer = new FileWriter(file);
In java, linebreaks use the character '\n', you can use that.
Load a byte array using String name:
Files.readAllBytes(path);
Or a file:
FileReader reader = new FileReader(file);
You'll have to come up for a system to name your files. To check if a file exists, just create the file object and call
file.exists() && !file.isDirectory()
For naming your files, you'll need to come up with a system. If recipeName is unique, you can use that. You'll find something that uniquely identifies your Recipe.

JavaFX app overwriting files while being open causes exception

I have a runnable jar file (with a lib folder housing all the dependency jars). This is located on a network share which anyone that has access can run from. This works great except one huge caveat. If I want to deploy a new version of the software, I have to ask everyone to exit the application first. This is because if I overwrite the jars with new versions (or if there is a network blip), the running program stays open but as soon as they do an action that requires code in of the dependencies (jar file in lib folder), it will cause an exception:
Exception in thread "JavaFX Application Thread" java.lang.NoClassDefFoundError
The program will not produce an error, but certain actions will break, like communicating with an API etc.
Is there a way that I can resolve this so that I can publish updates while the user's are working or at least produce a prompt that will force them to close/and reopen the app etc.
One approach:
Provide a script which launches the application from a local copy of the remote code.
Store a version number with your app.
The script checks if there is a local copy of the app on the machine.
If no local version exists, the script copies the jars from your network share to a local copy.
If there is already a local copy, it checks the version against the network version.
If the network version is updated, it overwrites the local copy with the new remote version before launching the app,
otherwise it just launches the local copy.
If you want the users to be alerted that they are currently running an outdated copy, you could create a JavaFX task which polls the remote version number and checks it against the currently running version number. If they differ, you can alert and (if you wish) shutdown the app and re-trigger the launcher script.
I was able to create a scheme in which I have multiple server folder locations that house the jar distributable. And this jar basically checks these locations for the latest copy of the application and runs that latest copy. I was able to get it working for both Mac and Windows (didn't test Linux) by detecting the OS.
So now, I can publish an update over the oldest app, and the next time the user opens the app, it will be the latest copy.
process.properties
location.a=Application/A
location.b=Application/B
app=app.jar
You can add folders A-Z but just add them into the properties.
Main.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
public class Main
{
public static Properties properties;
private static final String DEFAULT_PROPERTY_FILE_LOCATION = Paths.get("").toAbsolutePath().toString() + File.separator + "process.properties";
private static final String JAVE_EXEC;
static
{
String os = System.getProperty("os.name");
if (StringUtils.containsIgnoreCase(os, "win"))
{
JAVA_EXEC = "java";
} else if (StringUtils.containsIgnoreCase(os, "mac"))
{
JAVA_EXEC = "/usr/bin/java";
} else if (StringUtils.containsIgnoreCase(os, "nux") || StringUtils.containsIgnoreCase(os, "nix"))
{
JAVA_EXEC = "/usr/bin/java";
} else
{
JAVA_EXEC = "java";
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Main.properties = new Properties();
try
{
InputStream in = new FileInputStream(DEFAULT_PROPERTY_FILE_LOCATION);
Main.properties.load(in);
System.out.println("Loaded property file: " + DEFAULT_PROPERTY_FILE_LOCATION);
TreeMap<Long, String> locations = new TreeMap<>();
String appName = Main.properties.getProperty("app");
if (validateProperties(properties))
{
for (int letter = 'a'; letter <= 'z'; ++letter)
{
String location = "location." + (char) letter;
if (Main.properties.getProperty(location) != null)
{
String networkLocation = Paths.get("").toAbsolutePath() + File.separator + Main.properties.getProperty(location);
File file = new File(networkLocation + File.separator + appName);
if (file.exists())
{
locations.put(FileUtils.lastModified(file), networkLocation);
}
}
}
if (!locations.isEmpty())
{
Runtime.getRuntime().exec(new String[]
{
JAVA_EXEC, "-jar", locations.lastEntry().getValue() + File.separator + appName
}, null, new File(locations.lastEntry().getValue()));
}
}
} catch (IOException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static boolean validateProperties(Properties properties)
{
List<String> mandatoryProperties = new ArrayList<>();
mandatoryProperties.add("app");
for (String mandatoryProperty : mandatoryProperties)
{
if (properties.get(mandatoryProperty) == null)
{
System.out.println("Failed - Property: " + mandatoryProperty + " doesn't exist.");
return false;
}
}
return true;
}
}

Sort Apps according to usage in android (for CustomShareBottomSheetFragment)

Problem
I am trying to create a share intent chooser page [BottomSheetFragment] for sharing text in my app but i am unable to sort the apps according to the users most frequently used apps, the relevant app list is coming in random order. I want to implement it without taking any permission from the user.
From the photo we can see that Google photos is not using default Share Intent. Many other apps like Youtube are also doing the same but i couldn't find the code to sort the apps based on usage without permission.
Share text page in My App - WhatsApp should come on the first position according to usage.
Share photo page in Google Photos App
Code I tried had the following problems
Only Alphabetical sorting was available using the below code.
PackageManager pm = context.getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_SEND, null);
mainIntent.setType("text/plain");
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, PackageManager.MATCH_DEFAULT_ONLY);
Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));
I was able to do it by taking "android.permission.PACKAGE_USAGE_STATS" permission from the user. But i can't take this permission in my production app just for sharing a text.
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.UserHandle;
import android.util.Log;
import java.text.Collator;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class AppUsageUtil {
private static final String TAG = "AppUsageUtil";
/**
* Method
*
* #param apkPackageName
* #return Runtime.
*/
public static long getAppRuntime(String apkPackageName) {
long timeInForeground = 0;
try {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
long start = calendar.getTimeInMillis();
long end = System.currentTimeMillis();
Log.d(TAG, "start: "+ start);
Log.d(TAG, "end: "+ end);
UsageStatsManager usageStatsManager = (UsageStatsManager) BaseApplication.Companion.getContext().getSystemService(Context.USAGE_STATS_SERVICE);
Map<String, UsageStats> usageStats = usageStatsManager.queryAndAggregateUsageStats(start, end);
Log.d(TAG, "usageStats: "+ usageStats);
timeInForeground = usageStats.get(apkPackageName).getTotalTimeInForeground();
} catch (Exception e){
Log.d(TAG, "getAppRuntime: " + e.toString());
}
return timeInForeground;
}
public static class AppUsageNameComparator implements Comparator<ResolveInfo> {
public AppUsageNameComparator(List<ResolveInfo> resolveInfos) {
mCollator.setStrength(Collator.PRIMARY);
}
public final int compare(ResolveInfo resolveInfoA, ResolveInfo resolveInfoB) {
// We want to put the one targeted to another user at the end of the dialog.
long usage1 = getAppRuntime(resolveInfoA.activityInfo.packageName);
long usage2 = getAppRuntime(resolveInfoB.activityInfo.packageName);
return Long.compare(usage1, usage2);
}
private final Collator mCollator = Collator.getInstance();
}
}
Help will be appreciated. Thanks
Note: Someone had shared how to sort the apps alphabetically but i want to sort it based on usage. Relevant Link: Sort Android apps alphabetically?

How to get scrape using crawler4j?

I've been going at this for 4 hours now, and I simply can't see what I'm doing wrong. I have two files:
MyCrawler.java
Controller.java
MyCrawler.java
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.http.Header;
public class MyCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether the given url
* should be crawled or not (based on your crawling logic).
*/
#Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready to be processed
* by your program.
*/
#Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String domain = page.getWebURL().getDomain();
String path = page.getWebURL().getPath();
String subDomain = page.getWebURL().getSubDomain();
String parentUrl = page.getWebURL().getParentUrl();
String anchor = page.getWebURL().getAnchor();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Domain: '" + domain + "'");
System.out.println("Sub-domain: '" + subDomain + "'");
System.out.println("Path: '" + path + "'");
System.out.println("Parent page: " + parentUrl);
System.out.println("Anchor text: " + anchor);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
Header[] responseHeaders = page.getFetchResponseHeaders();
if (responseHeaders != null) {
System.out.println("Response headers:");
for (Header header : responseHeaders) {
System.out.println("\t" + header.getName() + ": " + header.getValue());
}
}
System.out.println("=============");
}
}
Controller.java
package edu.crawler;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.http.Header;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class Controller
{
public static void main(String[] args) throws Exception
{
String crawlStorageFolder = "../data/";
int numberOfCrawlers = 7;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/~welling/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.start(MyCrawler, numberOfCrawlers);
}
}
The Structure is as follows:
java/MyCrawler.java
java/Controller.java
jars/... --> all the jars crawler4j
I try to compile this on a WINDOWS machine using:
javac -cp "C:\xampp\htdocs\crawlcrowd\www\java\jars\*;C:\xampp\htdocs\crawlcrowd\www\java\*" MyCrawler.java
This works perfectly, and I end up with:
java/MyCrawler.class
However, when I type:
javac -cp "C:\xampp\htdocs\crawlcrowd\www\java\jars\*;C:\xampp\htdocs\crawlcrowd\www\java\*" Controller.java
it bombs out with:
Controller.java:50: error: cannot find symbol
controller.start(MyCrawler, numberOfCrawlers);
^
symbol: variable MyCrawler
location: class Controller
1 error
So, I think somehow I am not doing something that I need to be doing. Something that will make this new executable class be "aware" of the MyCrawler.class. I have tried fiddling with the classpath in the commandline javac part. I've also tried setting it in my environment variables.... no luck.
Any idea how I can get this to work?
UPDATE
I got most of this code from the Google Code page itself. But I just can't figure out what must go there. Even if I try this:
MyCrawler mc = new MyCrawler();
No luck. Somehow Controller.class does not know about MyCrawler.class.
UPDATE 2
I don't think it matters, due the problem clearly being that it can't find the class, but either way, here is the signature of "CrawlController controller". Taken from here.
/**
* Start the crawling session and wait for it to finish.
*
* #param _c
* the class that implements the logic for crawler threads
* #param numberOfCrawlers
* the number of concurrent threads that will be contributing in
* this crawling session.
*/
public <T extends WebCrawler> void start(final Class<T> _c, final int numberOfCrawlers) {
this.start(_c, numberOfCrawlers, true);
}
I am in fact passing through a "crawler" as I'm passing in "MyCrawler". The problem is that application doesn't know what MyCrawler is.
A couple of things come to mind:
Is your MyCrawler extending edu.uci.ics.crawler4j.crawler.WebCrawler?
public class MyCrawler extends WebCrawler
Are you passing in MyCrawler.class (i.e., as a class) into controller.start?
controller.start(MyCrawler.class, numberOfCrawlers);
Both of these need to be satisfied in order for the controller to compile and run. Also, Crawler4j has some great examples here:
https://code.google.com/p/crawler4j/source/browse/src/test/java/edu/uci/ics/crawler4j/examples/basic/BasicCrawler.java
https://code.google.com/p/crawler4j/source/browse/src/test/java/edu/uci/ics/crawler4j/examples/basic/BasicCrawlController.java
These 2 classes will compile and run right away (i.e., BasicCrawlController), so it's a good starting place if you are running into any issues.
The parameters for start() should be a class and number of crawlers. Its throwing an error as you are passing in an object of crawler and not the crawler class. Use the start method as shown below, it should work
controller.start(MyCrawler.class, numberOfCrawlers)
Here you are passing a class name MyCrawler as a parameter.
controller.start(MyCrawler, numberOfCrawlers);
I think class name should not be a parameter.
I am also working little bit on Crawling!

jAudio Feature Extractor : Null Exception

My project is to create an Android app that can perform feature extraction and classification of audio files. So first, I'm creating a Java application as a test run.
I'm attempting to use jAudio's feature extractor package to extract audio features from an audio file.
As a starter, I want to input a .wav file and run the feature extraction operation upon that file, and then store the results as an .ARFF file.
However, I'm getting the below NullPointer Exception error from a package within the project:
Exception in thread "main" java.lang.NullPointerException
at java.io.DataOutputStream.writeBytes(Unknown Source)
at jAudioFeatureExtractor.jAudioTools.FeatureProcessor.writeValuesARFFHeader(FeatureProcessor.java:853)
at jAudioFeatureExtractor.jAudioTools.FeatureProcessor.<init>(FeatureProcessor.java:258)
at jAudioFeatureExtractor.DataModel.extract(DataModel.java:308)
at Mfccarffwriter.main(Mfccarffwriter.java:70)
Initially I thought it was a file permission issue(i.e, the program was not being allowed to write a file because of lack of permissions), but even after granting every kind of permission to Eclipse 4.2.2(I'm running Windows 7, 64 bit version), I'm still getting the NullException bug.
The package code where the offending exception originates from is given below:
/**
* Write headers for an ARFF file. If saving for overall features, this must
* be postponed until the overall features have been calculated. If this a
* perWindow arff file, then all the feature headers can be extracted now
* and no hacks are needed.
* <p>
* <b>NOTE</b>: This procedure breaks if a feature to be saved has a
* variable number of dimensions
*
* #throws Exception
*/
private void writeValuesARFFHeader() throws Exception {
String sep = System.getProperty("line.separator");
String feature_value_header = "#relation jAudio" + sep;
values_writer.writeBytes(feature_value_header); // exception here
if (save_features_for_each_window && !save_overall_recording_features) {
for (int i = 0; i < feature_extractors.length; ++i) {
if (features_to_save[i]) {
String name = feature_extractors[i].getFeatureDefinition().name;
int dimension = feature_extractors[i]
.getFeatureDefinition().dimensions;
for (int j = 0; j < dimension; ++j) {
values_writer.writeBytes("#ATTRIBUTE \"" + name + j
+ "\" NUMERIC" + sep);
}
}
}
values_writer.writeBytes(sep);
values_writer.writeBytes("#DATA" + sep);
}
}
Here's the main application code:
import java.io.*;
import java.util.Arrays;
import com.sun.xml.internal.bind.v2.runtime.RuntimeUtil.ToStringAdapter;
import jAudioFeatureExtractor.Cancel;
import jAudioFeatureExtractor.DataModel;
import jAudioFeatureExtractor.Updater;
import jAudioFeatureExtractor.Aggregators.AggregatorContainer;
import jAudioFeatureExtractor.AudioFeatures.FeatureExtractor;
import jAudioFeatureExtractor.AudioFeatures.MFCC;
import jAudioFeatureExtractor.DataTypes.RecordingInfo;
import jAudioFeatureExtractor.jAudioTools.*;
public static void main(String[] args) throws Exception {
// Display information about the wav file
File extractedFiletoTest = new File("./microwave1.wav");
String randomID = Integer.toString((int) Math.random());
String file_path = "E:/Weka-3-6/tmp/microwave1.wav";
AudioSamples sampledExampleFile = new AudioSamples(extractedFiletoTest,randomID,false);
RecordingInfo[] samplefileInfo = new RecordingInfo[5];
samplefileInfo[1] = new RecordingInfo(randomID, file_path, sampledExampleFile, true);
double samplingrate= sampledExampleFile.getSamplingRateAsDouble();
int windowsize= 4096;
boolean normalize = false;
OutputStream valsavepath = new FileOutputStream(".\\values");
OutputStream defsavepath = new FileOutputStream(".\\definitions");
boolean[] featurestosaveamongall = new boolean[10];
Arrays.fill(featurestosaveamongall, Boolean.TRUE);
double windowoverlap = 0.0;
DataModel mfccDM = new DataModel("features.xml",null);
mfccDM.extract(windowsize, 0.5, samplingrate, true, true, false, samplefileInfo, 1); /// invokes the writeValuesARFFHeader function.
}
}
You can download the whole project (done so far)here.
This may be a bit late but I had the same issue and I tracked it down to the featureKey and featureValue never being set in the DataModel. There is not a set method for these but they are public field. Here is my code:
package Sound;
import jAudioFeatureExtractor.ACE.DataTypes.Batch;
import jAudioFeatureExtractor.DataModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Analysis {
private static String musicFile = "/home/chris/IdeaProjects/AnotherProj/res/SheMovesInHerOwnWay15s.wav";
private static String featureFile = "/home/chris/IdeaProjects/AnotherProj/res/features.xml";
private static String settingsFile = "/home/chris/IdeaProjects/AnotherProj/res/settings.xml";
private static String FKOuputFile = "/home/chris/IdeaProjects/AnotherProj/res/fk.xml";
private static String FVOuputFile = "/home/chris/IdeaProjects/AnotherProj/res/fv.xml";
public static void main(String[] args){
Batch batch = new Batch(featureFile, null);
try{
batch.setRecordings(new File[]{new File(musicFile)});
batch.getAggregator();
batch.setSettings(settingsFile);
DataModel dm = batch.getDataModel();
OutputStream valsavepath = new FileOutputStream(FVOuputFile);
OutputStream defsavepath = new FileOutputStream(FKOuputFile);
dm.featureKey = defsavepath;
dm.featureValue = valsavepath;
batch.setDataModel(dm);
batch.execute();
}
catch (Exception e){
e.printStackTrace();
}
}
}
I created the settings.xml file using the GUI and just copied the features.xml file from the directory where you saved the jar.
Hope this helps

Categories

Resources