2013年3月5日火曜日

壊れたMP3を少し治す

前に自作したダウンローダを利用して保存していたmp3データが壊れていた。

理由はダウンローダにバグがあり、ところどころに0が入っていてノイズになる。
mp3の構造を調べないといけないのかなと思いつつ、とりあえず0を除くプログラムを組んだ。
ちょっとだけましだった


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Repair {

 private File file;
 private int checkByte = 5;
 private int checkByte2 = 4;

 public Repair(File file) {
  this.file = file;
  if (!this.file.isFile())
   this.file = null;
 }

 public Repair(String file) {
  this.file = new File(file);
  if (!this.file.isFile())
   this.file = null;
 }

 public long execute() throws Exception {
  System.out.println("Repair");
  if (file == null)
   return -1;
  long start = System.currentTimeMillis();
  FileInputStream fis = new FileInputStream(file);
  File repair = new File(file.getAbsoluteFile() + ".repair.mp3");
  int d = 0;
  while (repair.isFile()) {
   repair = new File(file.getAbsoluteFile() + "." + Integer.toString(d++) + ".repair.mp3");
  }
  FileOutputStream fos = new FileOutputStream(repair);
  int ocount;
  int counter = 0;
  boolean skip = false;
  boolean wait = false;
  Integer ch;
  byte[] zerobuf = new byte[checkByte];
  byte[] buf = new byte[checkByte2];
  int zerosize = 0;
  int bufsize = 0;
  boolean first = true;
  while ((ch = fis.read()) != -1) {

   /////////
   if (first) {
    if (skip)
     if (ch != 0) {
      skip = false;
      first=false;
     }
    if (first)
     if (!skip) {
      if (ch == 0) {
       wait = true;
      } else {
       wait = false;
      }
      if (wait) {
       zerobuf[zerosize++] = 0;
       if (zerosize == checkByte) {
        //System.out.print("skip");
        skip = true;
        zerosize = 0;
       }
      } else {
       fos.write(ch);
       if (zerosize != 0) {
        fos.write(zerobuf, 0, zerosize);
        zerosize = 0;
       }
      }
     }
   }

   if (!first) {
    if (skip)
     if (ch != 0) {
      skip = false;
     }

    if (!skip) {

     buf[counter] = ch.byteValue();
     //System.out.println("byte"+buf[counter]);
     //System.out.println("\tInt->"+ch);
     //Thread.sleep(500);
     if (counter++ == checkByte2 - 1) {
      counter = 0;
      ocount = 0;
      for (int i = 0; i < checkByte2; i++) {
       if (buf[i] == 0) {
        ocount++;
       }
      }
      if (ocount == checkByte2) {
       //System.out.println("0 skipを見つけました");
       skip = true;
      } else
       fos.write(buf);
     }
    }

   }
  }
  fos.close();
  fis.close();
  return System.currentTimeMillis() - start;
 }

}

0 件のコメント:

コメントを投稿