I am getting the FFT back on an audio file, but it doesn't take into account the time in the song that that frequency occurred. I first tried getting the length of the file, and then spreading the FFT results equally over the track length, but that might be wrong and not give the correct frequencies back. So now I am trying to get the file split up into 1 second chunks and then return the frequency for that second alone, and then I will store that in a database to save it.
But I have no clue on how to save it, all other threads I have found and research I have done only shows how to break into x amount of parts, not per second as in a song. Is there a way to do this?
Sorry if this is a trivial topic, but I am very new to Java and programming, so this is quite a struggle for me.
Thanks in advance
Here is my code so far:
File file = new File(FILENAME);
float durationInSeconds = 0;
Tag tag;
java.util.logging.Logger.getLogger("org.jaudiotagger").setLevel(Level.OFF);
AudioFile audioFile;
try {
audioFile = AudioFileIO.read(file);
System.out.println("Track length = " + audioFile.getAudioHeader().getTrackLength());
durationInSeconds = audioFile.getAudioHeader().getTrackLength();
} catch (CannotReadException | TagException | ReadOnlyFileException
| InvalidAudioFrameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
convert();
System.out.println(((durationInSeconds)/endResult.length)*1000);
for(int i = 0; i < endResult.length; i++) {
Thread.sleep((long) (((durationInSeconds)/endResult.length)*1000));
System.out.println(endResult[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I have a nested arraylist consisting of Productname and price within a while loop that Im trying to send to Apache POI Java program in eclipse to create a MS word invoice from my cart items. Problem is, only two items are being written into the word document and it seems the remaining function calls are not taking place to add further products and price. How do I fix this issue? Is there a way to reduce function calls? Im a beginner and this is a really important piece of code for my project. Please help
Here is my code:-
Iterator<ArrayList<String>> itr = bl.iterator();
while(itr.hasNext())
{
ArrayList<String> al = itr.next();
try {
n=z.writeData(al.get(0), al.get(1));
} catch (IOException e) {
e.printStackTrace();
}
try {
z.closeFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Runtime rt = Runtime.getRuntime();
try {
rt.exec("C:\\Program Files (x86)\\Microsoft Office\\Office12\\winword.exe C:\\Users\\kaustav\\Desktop\\"+n+".docx");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
my code to generate the product price and name-
public int writeData(String name, String price) throws IOException
{
paragraph=document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setFontSize(20);
run.setTextPosition(40);
run.setText(name+" "+price);
document.write(out);
return n;
}
the output should be that under Product name more than 2 items should be named and under Product Price their respective prices in my MS Word document but I only get upto 2 products and their prices. The remaining are not written into my MS Word document. Please help !!
I have many byte[] pieces to write to a file and these pieces are kinda big and I think the bytes are getting mixed...
Is there any methods to wait for .write(byte[]) to finish his work or other ways to deal with this problem?
When I watch the file the first half is ok , then when I start writing the second half, some time it ends with the first half.... The byte array is good, I tested them.
If you need any explain of code feel free ask.
try (FileOutputStream fos = new FileOutputStream(Main.newFile)) {
for (int y = 0; y < piecesCount; y++) {
if (this.myList[y] == 1) {
fos.write(this.piecesArray.get(y).piece);
fos.flush();
System.out.println("Im writing " + y + " piece");
} else {
y--;
}
}
fos.close();
} catch (FileNotFoundException ex) {
} catch (IOException | InterruptedException ex) {
}
Well, if piecesCount is a long the int y variable may overflow and start wrtiting the first part of the array.
If this is not the case, I don't see other bugs in this code that may cause what you described. In which case there must be something going on in
piecesArray.get(y).piece
OK I am using the following function to create multiple threads to download a file. You can see the functions takes link, starting byte, ending byte and the path to download the file as argument. I call this function 2 times to create two threads to download the required file.
For example, if the file is of 100 bytes I do the following
thread-1 --> DownloadFile("http://localhost/file.zip", 0, 50, "output.zip");
thread-2 --> DownloadFile("http://localhost/file.zip", 50, 100, "output.zip");
But you know what happens, only a few bytes don't get downloaded and my progress bar gets stuck at 99%. That's the problem!!!
Why it gets stuck at 99%? In words why some bytes are being lost? I could see the total number of bytes in the downloaded variable.
Here is the function
public void DownloadFile(final String link, final long start,final long end, final String path){
new Thread(new Runnable(){
public void run(){
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Range", "bytes="+start+"-"+end);
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
RandomAccessFile raf = new RandomAccessFile(path,"rw");
raf.seek(start);
int i=0;
byte bytes[] = new byte[1024];
while((i = bis.read(bytes))!=-1){
raf.write(bytes, 0, i);
downloaded = downloaded+i;
int perc = (int) ((downloaded*100)/FileSize);
progress.setValue(perc);
percentLabel.setText(Long.toString(downloaded)+" out of "+FileSize);
}
if(FileSize==downloaded){
progress.setValue(100);
JOptionPane.showMessageDialog(null, "Download Success! ");
progress.setValue(0);
downloaded=0;
downBtn.setText("Download");
}
bis.close();
raf.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
Thanks in anticipation.
RandomAccessFile is not thread safe.
raf.seek(begin) fails, see the documentation of RandomAccessFile.seek()
Sets the file-pointer offset, measured from the beginning of this
file, at which the next read or write occurs. The offset may be set
beyond the end of the file. Setting the offset beyond the end of the
file does not change the file length. The file length will change only
by writing after the offset has been set beyond the end of the file.
You may download parts of file into separate files then merge them.
Are you sure that parallel downloads are faster?
I have got a .txt file which stores a players' money. I need this file to increment or detriment a certain amount depending on if the player kills something or if they buy something from the shop.
The issue is that I do not know how to actually increment or detriment the contents. I can delete/recreate the .txt file with the new money, however because multiple threads will be accessing the file, then there is the risk that the file may not exist due to it being deleted and not regenerated yet.
Just to clarify, there will only be one thread at a time modifying the file. Other threads will only be reading the file.
So how would I do this without deleting the data/file first?
Here is the code ,read file first and then increment it and store again -
BufferedWriter out = null;
try {
// Read File Contents - score
BufferedReader br = new BufferedReader(new FileReader("c:\\a.txt"));
String storedScore="0";
int storedScoreNumber = 0;
while ((storedScore = br.readLine()) != null) {
storedScoreNumber=(Integer.parseInt(storedScore==null?"0":storedScore));
}
// Write File Contents - incremented socre
out = new BufferedWriter(new FileWriter("c:\\a.txt", false));
out.write(String.valueOf(storedScoreNumber+1));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Have a singleton data accessor with a queue so that it is the only one manipulating the file. If necessary acknowledge to client threads after the write.
I am trying to read a wav file into an array and then write it on a text file using android application. To validate that the values on the text file are correct, I compare it with Matlab.
I used the same code in Android and Java, and in both cases the results are different, by different I mean that Android saves only 5946 readings out of 20000 readings. On the other hand, when I run the Java code, I get the full 20000 readings !
I have no idea why I get 5946 readings when I run the Android application, while I get 20000 readings when I run the java code. Is there any limitation on the text file size?
Following is the code I wrote (plz note that I use a library for wav file reading):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/////////////////////
Done = (TextView) findViewById(R.id.textView1);
Done.setText("processing");
double[] buffer;
int len;
///Reading the wav file into buffer/////
filePath = "mnt/sdcard";
File filein = new File(filePath, "audio.wav");
try
{
// Open the wav file specified as the first argument
WavFile wavFile = WavFile.openWavFile(filein);
// Display information about the wav file
wavFile.display();
// Get the number of audio channels in the wav file
int numChannels = wavFile.getNumChannels();
// Create a buffer of 100 frames
buffer = new double[20000 * numChannels];
int framesRead;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
do
{
// Read frames into buffer
framesRead = wavFile.readFrames(buffer, 20000);
// Loop through frames and look for minimum and maximum value
for (int s=0 ; s<framesRead * numChannels ; s++)
{
if (buffer[s] > max) max = buffer[s];
if (buffer[s] < min) min = buffer[s];
}
len=buffer.length;
}
while (framesRead != 0);
// Close the wavFile
wavFile.close();
// Output the minimum and maximum value
System.out.printf("Min: %f, Max: %f\n", min, max);
//////////////Saving the array (buffer) into a text file (before.txt)////////
filePath = "mnt/sdcard";
for (int i=0; i<20000; i++)
{
if(fout==null)
try {
fout=new DataOutputStream(new FileOutputStream(new File(filePath,"before.txt")));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str=Double.toString(buffer[i])+" " ;
//Log.v(str,Double.toString(i));
try {
fout.writeBytes(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
System.err.println(e);
}
if(fout!=null)
{
try {
fout.flush();
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Done.setText("Done");
}
I found that the size of the text file on the smartphone is around 300 KB, However, when I browse it from the PC it is 100KB !
It seems that the system keeps the same size every time I write on it !
Reboot of the phone solved the issue. (Android MTP support does not show recent files until the device is rebooted).
https://code.google.com/p/android/issues/detail?id=38282