I am working on my final project, hence I need to read wav file - I succeed to do it.
When I run the code in java it is take less then 1 sec, but when I try to run the code on Nexus 5, it is take almost 1 minute!!
It is take a lot of time to copy the (sb.get(i)) to original_signal[i].
for (int i = 0; i < 1710080; i++) {
original_signal[i] = (sb.get(i));
}
Please, need help,
Thanks!!!
public static void jjjj(){
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ilia.wav";
Wave wave = new Wave(filepath);
byte[] arr = wave.getBytes();
System.out.println();
wave.length();
ByteBuffer bb = ByteBuffer.wrap(arr);
System.out.println(bb.capacity());
bb.order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer sb = bb.asShortBuffer();
original_signal = new double[1710080];
// double firstSample;
//THIS FOR LOOP TAKE A LOF OF TIME
for (int i = 0; i < 1710080; i++) {
original_signal[i] = (sb.get(i));
}
System.out.println("sss");
}
I solved the issue
Wave wave = new Wave(filepath);
double[] original_signal = wave.getNormalizedAmplitudes();
System.out.println(wave.getWaveHeader());
Parameters.Fs = wave.getWaveHeader().getSampleRate();
return original_signal;
Related
For my Java class, I'm working on a project that is essentially a database for MTG cards. I have to read from a file as part of the project, so I am reading the card information from a file, and then splitting the lines to put each different type of information together to form different object classes for the different types of cards. The main nitpicky issue I'm running into right now is that I need the card text to be on one line in the text file so I can read it line by line, but I'd prefer if it weren't all on one line when I print it to the console. Is there any way to add a character combination into the text of the file itself that will tell my compiler, "line break here," when it reads that, or am I out of luck? I know I could just use \n in the code to achieve this, but as I am looping through the file, there is no way to do so properly that I know of, as not every card's text needs line breaks inserted. If it matters, this is the chunk of my code that deals with that:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class MTG {
public static void main(String[] args) {
int creatureLength = 4;
//Prompt User
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Magic: the Gathering card database. This tool currently supports Rare and Mythic Rare cards from the Throne of Eldraine Expansion.");
try {
System.out.println("\nSelect the card type you'd like to view.");
System.out.println(""
+ "(1)Creatures\n"
);
int choice = Integer.parseInt(sc.next());
//Choose type
//Creatures
if(choice == 1){
Creature[] creatures = creatureGen("textfiles/Creatures.txt", creatureLength);
System.out.println("\nViewing creatures. Which card would you like to view?: \n");
for(int k = 0; k < creatureLength; k++) {
System.out.println(
"(" + (k + 1) + ") " + creatures[k].getName());
}
int creatureChoice = Integer.parseInt(sc.next());
try {
System.out.println("\n" + creatures[(creatureChoice - 1)]);}
catch(Exception e) {
System.out.println("Input was not a specified number. Exiting...");
}
}
}
catch(NumberFormatException ex){
System.out.println("Input was not a specified number. Exiting...");
}
sc.close();
}
//Read Creature text file
public static Creature[] creatureGen(String path, int length) {
Creature[] creatures = new Creature[length];
try {
FileReader file = new FileReader(path);
BufferedReader reader = new BufferedReader(file);
String name[] = new String[length];
String cost[] = new String[length];
String color[] = new String[length];
String type[] = new String[length];
String cTypes[] = new String[length];
String tags[] = new String[length];
String text[] = new String[length];
int power[] = new int[length];
int toughness[] = new int[length];
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
name[i] = line.split("\\|")[0];
cost[i] = line.split("\\|")[1];
color[i] = line.split("\\|")[2];
type[i] = line.split("\\|")[3];
cTypes[i] = line.split("\\|")[4];
tags[i] = line.split("\\|")[5];
text[i] = line.split("\\|")[6];
power[i] = Integer.parseInt(line.split("\\|")[7]);
toughness[i] = Integer.parseInt(line.split("\\|")[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
reader.close();
}
catch (Exception e) {
System.out.println("Error reading file: " + path);
}
return creatures;
}
}
The Creature object class essentially just stores the data that I am putting into it with the creatureGen method. A sample line from the text file I am reading from looks something like this:
Charming Prince|1W|White|Creature|Human Noble||When Charming Prince enters the battlefield, choose one — • Scry 2. • You gain 3 life. • Exile another target creature you own. Return it to the battlefield under your control at the beginning of the next end step.|2|2
It would be ideal to be able to insert line breaks after each of the bullet points in this card, for example, but as I said earlier, I need the text to be in one line for my loop to read it. Is there any way around this when I print this back to the console? I appreciate any help.
Just replace those bullet points with line breaks :
text[i] = line.split("\\|")[6].replaceAll("•","\n");
Also, you should not split each time you need an element, put the result of line.split("\|") in a String[] variable and use it afterwards.
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
String[] elements = line.split("\\|");
name[i] = elements[0];
cost[i] = elements[1];
color[i] = elements[2];
type[i] = elements3];
cTypes[i] = elements[4];
tags[i] = elements[5];
text[i] = elements[6].replaceAll("•","\n");
power[i] = Integer.parseInt(elements[7]);
toughness[i] = Integer.parseInt(elements[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
Finally, about vocabulary, the compiler is not reading your file. The compiler translates your code into binary instructions for the processor (to summarize).
Your file is read at runtime.
I'm working on this method that gets data from a csv file and stores them into arrays. The code I have compiles but the values for every array are "null". I have no idea why this is happening.
The csv file looks like this but continues for 91 lines:
sunday,9/1/2016,,,,,16:00,20:00
monday,9/2/2016,8:00,12:00,,,,
tuesday,9/3/2016,8:00,12:00,12:00,16:00,,
Wednesday,9/4/2016,,,,,16:00,20:00
thursday,9/5/2016,8:00,12:00,,,,
Friday,9/6/2016,,,12:00,16:00,,
Saturday,9/7/2016,,,,,16:00,20:00
public static void getData() throws FileNotFoundException {
File timeSheets = new File("timeSheets.csv");
Scanner ts = new Scanner(timeSheets);
int n = 0, c = 0;
String temp;
while (ts.hasNext()) {
temp = ts.nextLine();
c++;
}
String[] field = new String[8];
String[] day = new String[c];
String[] date = new String[c];
Integer[] morn = new Integer[c];
Integer[] after = new Integer[c];
Integer[] night = new Integer[c];
while (ts.hasNext()) {
temp = ts.nextLine();
field = temp.split(",");
day[n] = field[0];
date[n] = field[1];
if (field[4].equals("")) {
morn[n] = 0;
} else {
morn[n] = (int) (Double.parseDouble(field[4].replace(":", "."))
- Double.parseDouble(field[3].replace(":", ".")));
}
if (field[6].equals("")) {
after[n] = 0;
} else {
after[n] = (int) (Double.parseDouble(field[6].replace(":", "."))
- Double.parseDouble(field[5].replace(":", ".")));
}
if (field[8].equals("")) {
night[n] = 0;
} else {
night[n] = (int) (Double.parseDouble(field[8].replace(":", "."))
- Double.parseDouble(field[7].replace(":", ".")));
}
n++;
}
System.out.print(day.length);
System.out.println();
for (int i = 0; i < day.length; i++) {
System.out.println(day[i]);
}
ts.close();
}
I just try to run your code. I see that the second while have been never looped. The method ts.hasNext() always return false. Because the stream resource has been read in the first while and it was closed.
Solution: you should initialize object scanner again.
Note: you can verify what i said by printing scanner object. You will get the result such as:
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=238][match valid=false][need input=false][source closed=true][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]7
You're not reading the file. new File("timeSheets.csv") only creates a reference to a file. You have to read the contents of that file.
There are plenty of libraries that make doing this easy. The basic class in rt.jar that offers this functionality is FileReader.
public static FAQ_Alisa_QnA[] oipReadQuestion(){
String questionA1,thisUser;
int indexQuestion;
String [] entryDetails;
FAQ_Alisa_QnA [] entries = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File file = new File ("ReadOIP.txt");
int count = 0;
try{
Scanner sc = new Scanner(file);
//do this while there is a next line in file.
while(sc.hasNextLine()){
String line = sc.nextLine();
entryDetails = line.split(";");
// index = entryDetails[0];
indexQuestion = Integer.parseInt(entryDetails[0]);
thisUser = entryDetails[1];
questionA1 = entryDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexQuestion = indexQuestion;
a.thisUsername = thisUser;
a.questionA1 = questionA1;
entries [count] = a;
count++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA [] allQuestions = new FAQ_Alisa_QnA [count];
for(int i = 0; i < count; i++){
allQuestions[i] = entries[i];
}
return allQuestions;
}
public static FAQ_Alisa_QnA[] oipReadAnswers(){
String indexAnswer, answer11, thisUser;
String [] answerDetails;
FAQ_Alisa_QnA [] answers = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File thisFile = new File ("AnsReadOIP.txt");
int count1 = 0;
try{
Scanner sc1 = new Scanner(thisFile);
//do this while there is a next line in file.
while(sc1.hasNextLine()){
String line = sc1.nextLine();
answerDetails = line.split(";");
// index = entryDetails[0];
indexAnswer = answerDetails[0];
thisUser = answerDetails[1];
answer11 = answerDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexAnswer = Integer.parseInt(indexAnswer);
a.thisUsername = thisUser;
a.answer11 = answer11;
answers [count1] = a;
count1++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA[] allAnswers = new FAQ_Alisa_QnA[count1];
for(int i = 0; i < count1; i++){
allAnswers[i] = answers[i];
}
return allAnswers;
}
public static void oipPrintQnA(){
FAQ_Alisa_QnA [] allQuestions = oipReadQuestion();
FAQ_Alisa_QnA [] allAnswers = oipReadAnswers();
System.out.println("Organization in project work");
System.out.println("=============================");
for(int i = 0; i < allQuestions.length; i++){
System.out.println( allQuestions[i].indexQuestion + "-" + "Question" + ":");
System.out.println(allQuestions[i].thisUsername + ":" +allQuestions[i].questionA1);
System.out.println(" ");
for(int j = 0; j < allAnswers.length; j++){
if(allQuestions[i].indexQuestion == allAnswers[j].indexAnswer){
System.out.println("Answer for question "+ + allAnswers[j].indexAnswer+ ":" );
System.out.println(allAnswers[j].thisUsername+ ":" +allAnswers[j].answer11);
System.out.println(" ");
}
}
}
}
//So I have read answers and questions and I saved my qns and answers in 2 different text files. This is because I have add functions to it but i never put it here cuz my qn is not related to that. I just wanna know how to print out the qn and answer in 2 lines so that if the qn is so long then it can print out in two lines//
So these are how my text files look like:
ReadOIP.txt
1;Shafiq;How to organize your time well when you're juggling with so many project work and assignments on the same day? Best answer:The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment.
2;Rohannah;Does having a timetable works to finish your project on time?
3;lymeoww;Is task allocation really important to be organized in project work?
AnsReadOIP.txt
1;Andy23;The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment .2; Does having a timetable to do your project works? //For example this line, it will print out very long on the console//
2;Betty23;of course it does!
1;Ying Qian;just organize lorh
3;lymeoww;Yes, it is important!
//Refer to this picture//
I'm reading a couple images with the exact same name but numbered from 1-6 so I've used and array to read in the images, for example AstroWalkLeft1, AstroWalkLeft2 into arimgAstroWalkleft[]. This is what I have:
public void GetImages() {
imgMonster = new ImageIcon("Assets\\MonsterSingle.png").getImage();
for (int i = 1; i <= nASTROIMGMAX; i++) {
arimgAstroWalkLeft[i] = new ImageIcon("Assets\\AstroWalkLeft" + i + ".png").getImage();
arimgAstroWalkRight[i] = new ImageIcon("Assets\\AstroWalkRight" + i + ".png").getImage();
}
imgAstroStandLeft = new ImageIcon("Assets\\AstroStandLeft.png").getImage();
imgAstroStandRight = new ImageIcon("Assets\\AstroStandRight.png").getImage();
imgBackground1 = new ImageIcon("Assets\\Hallway.png").getImage();
imgBackground2 = new ImageIcon("Assets\\Observation Room.png").getImage();
}
My problem is replacing the numbers in the image's name to the variable in my loop. I'm wonder how I put that variable in where the number once was.
I am trying to take multiple multi-page .tif files and combine them into a single multi-page tif file.
I found some code in this question, but it only seems to take the first page of each individual .tif file and create the new multi-page .tif with those first pages.
Is there a small change I'm not seeing that would cause this same code to grab every page from the source .tif files and put them all into the combined .tif?
To clarify, I would like the source files:
SourceA.tif (3 pages)
SourceB.tif (4 pages)
SourceC.tif (1 page)
to be combined into
combined.tif (8 pages)
I would also like to be able to specify a resolution and compression of the .tif, but I'm not sure if JAI supports that and it's not a necessity for a correct answer.
The code from the referenced question, modified by me to load all the .tif files in a directory, is below for easy answering:
public static void main(String[] args) {
String inputDir = "C:\\tifSources";
File sourceDirectory = new File(inputDir);
File file[] = sourceDirectory.listFiles();
int numImages = file.length;
BufferedImage image[] = new BufferedImage[numImages];
try
{
for (int i = 0; i < numImages; i++)
{
SeekableStream ss = new FileSeekableStream(file[i]);
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
PlanarImage op = new NullOpImage(decoder.decodeAsRenderedImage(0), null, null, OpImage.OP_IO_BOUND);
image[i] = op.getAsBufferedImage();
}
TIFFEncodeParam params = new TIFFEncodeParam();
OutputStream out = new FileOutputStream(inputDir + "\\combined.tif");
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
List<BufferedImage> imageList = new ArrayList<BufferedImage>();
for (int i = 0; i < numImages; i++)
{
imageList.add(image[i]);
}
params.setExtraImages(imageList.iterator());
encoder.encode(image[0]);
out.close();
}
catch (Exception e)
{
System.out.println("Exception " + e);
}
}
I knew I was just missing some little part about iterating over the pages in a single .tif, I just wasn't sure where it was.
More searching on the internet led me to find that rather than doing:
PlanarImage op = new NullOpImage(decoder.decodeAsRenderedImage(0), null, null, OpImage.OP_IO_BOUND);
I wanted to iterate over every page in the current document with something like:
int numPages = decoder.getNumPages();
for(int j = 0; j < numPages; j++)
{
PlanarImage op = new NullOpImage(decoder.decodeAsRenderedImage(j), null, null, OpImage.OP_IO_BOUND);
images.add(op.getAsBufferedImage());
}
This adds every page of every .tif into the images List. One final trap was that the final call to
encoder.encode(images.get(0));
Would cause the first page to be in the new .tif twice, so I added an intermediate loop and List population that doesn't add the first page in the call to:
params.setExtraImages(imageList.iterator());
which keeps the first page out of the "ExtraImages" and it gets added with the call to encode.
Final updated code is:
public static void main(String[] args) {
String inputDir = "C:\\tifSources";
File faxSource = new File(inputDir);
File file[] = faxSource.listFiles();
System.out.println("files are " + Arrays.toString(file));
int numImages = file.length;
List<BufferedImage> images = new ArrayList<BufferedImage>();
try
{
for (int i = 0; i < numImages; i++)
{
SeekableStream ss = new FileSeekableStream(file[i]);
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
int numPages = decoder.getNumPages();
for(int j = 0; j < numPages; j++)
{
PlanarImage op = new NullOpImage(decoder.decodeAsRenderedImage(j), null, null, OpImage.OP_IO_BOUND);
images.add(op.getAsBufferedImage());
}
}
TIFFEncodeParam params = new TIFFEncodeParam();
OutputStream out = new FileOutputStream(inputDir + "\\combined.tif");
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
List<BufferedImage> imageList = new ArrayList<BufferedImage>();
for (int i = 1; i < images.size(); i++)
{
imageList.add(images.get(i));
}
params.setExtraImages(imageList.iterator());
encoder.encode(images.get(0));
out.close();
}
catch (Exception e)
{
System.out.println("Exception " + e);
}
}