public void testDeleteFields() throws Exception {
    // Delete using generic key
    File testFile = AbstractTestCase.copyAudioToTmp("test1.wma", new File("testDeleteFields.wma"));
    AudioFile f = AudioFileIO.read(testFile);
    List<TagField> tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT);
    assertEquals(0, tagFields.size());
    f.getTag().addField(FieldKey.ALBUM_ARTIST_SORT, "artist1");
    tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT);
    assertEquals(1, tagFields.size());
    f.getTag().deleteField(FieldKey.ALBUM_ARTIST_SORT);
    f.commit();

    // Delete using flac id
    f = AudioFileIO.read(testFile);
    tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT);
    assertEquals(0, tagFields.size());
    f.getTag().addField(FieldKey.ALBUM_ARTIST_SORT, "artist1");
    tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT);
    assertEquals(1, tagFields.size());
    f.getTag().deleteField("WM/AlbumArtistSortOrder");
    tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT);
    assertEquals(0, tagFields.size());
    f.commit();

    f = AudioFileIO.read(testFile);
    tagFields = f.getTag().getFields(FieldKey.ALBUM_ARTIST_SORT);
    assertEquals(0, tagFields.size());
  }
  /**
   * Parse the tmp file for tag data and create associated song
   *
   * @param dfi
   * @return song created from tag data
   */
  public static Song parseFileForSong(DiskFileItem dfi) { // TODO Think about where to move this.
    File audioFile = new File(dfi.getStoreLocation().toString().replace(".tmp", ".mp3"));
    //	"."+dfi.getContentType().substring(dfi.getContentType().indexOf("/")+1)));

    if (!dfi.getStoreLocation().renameTo(audioFile)) {
      log.error(
          "rename failed - store location:" + dfi.getStoreLocation() + ", audio file:" + audioFile);
    }

    AudioFile f = null;
    try {
      f = AudioFileIO.read(audioFile);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Tag tag = f.getTag();
    if (tag == null) {
      tag = f.getTagOrCreateAndSetDefault();
    }
    Song song = new Song();
    try {
      song.setArtist(tag.getFirst(FieldKey.ARTIST));
      song.setAlbum(tag.getFirst(FieldKey.ALBUM));
      song.setTitle(tag.getFirst(FieldKey.TITLE));
      song.setYear(tag.getFirst(FieldKey.YEAR));
      song.setTrack(tag.getFirst(FieldKey.TRACK));
      song.setFilename(dfi.getName());
    } catch (KeyNotFoundException knfe) {
      log.error("song key not found", knfe);
    }
    return song;
  }
  /**
   * Prechecks before normal write
   *
   * <p>
   *
   * <ul>
   *   <li>If the tag is actually empty, remove the tag
   *   <li>if the file is not writable, throw exception
   *   <li>
   *   <li>If the file is too small to be a valid file, throw exception
   *   <li>
   * </ul>
   *
   * @param af
   * @throws CannotWriteException
   */
  private void precheckWrite(AudioFile af) throws CannotWriteException {
    // Preliminary checks
    try {
      if (af.getTag().isEmpty()) {
        delete(af);
        return;
      }
    } catch (CannotReadException re) {
      throw new CannotWriteException(
          ErrorMessage.GENERAL_WRITE_FAILED.getMsg(af.getFile().getPath()));
    }

    if (!af.getFile().canWrite()) {
      logger.severe(ErrorMessage.GENERAL_WRITE_FAILED.getMsg(af.getFile().getPath()));
      throw new CannotWriteException(
          ErrorMessage.GENERAL_WRITE_FAILED.getMsg(af.getFile().getPath()));
    }

    if (af.getFile().length() <= MINIMUM_FILESIZE) {
      logger.severe(
          ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_IS_TOO_SMALL.getMsg(
              af.getFile().getPath()));
      throw new CannotWriteException(
          ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_IS_TOO_SMALL.getMsg(
              af.getFile().getPath()));
    }
  }
  public void testWriteToRelativeMp3File() {
    File orig = new File("testdata", "testV1.mp3");
    if (!orig.isFile()) {
      System.err.println("Unable to test file - not available");
      return;
    }

    File testFile = null;
    Exception exceptionCaught = null;
    try {
      testFile = AbstractTestCase.copyAudioToTmp("testV1.mp3");

      // Copy up a level coz we need it to be in same folder as working directory so can just
      // specify filename
      File outputFile = new File(testFile.getName());
      boolean result = copy(testFile, outputFile);
      assertTrue(result);

      // make Relative
      assertTrue(outputFile.exists());
      // Read File okay
      AudioFile af = AudioFileIO.read(outputFile);

      // Create tag and Change File
      af.getTagOrCreateAndSetDefault();
      af.getTag().setField(ArtworkFactory.createArtworkFromFile(new File("testdata/coverart.jpg")));
      af.commit();

    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }

    assertNull(exceptionCaught);
  }
  /** Lets now check the value explicity are what we expect */
  public void testTagFieldKeyWrite2() {
    Exception exceptionCaught = null;
    try {
      File testFile = AbstractTestCase.copyAudioToTmp("test1.wma", new File("testwrite1.wma"));
      AudioFile f = AudioFileIO.read(testFile);
      AudioFileIO.delete(f);

      // test fields are written with correct ids
      f = AudioFileIO.read(testFile);
      Tag tag = f.getTag();
      for (FieldKey key : FieldKey.values()) {
        if (!(key == FieldKey.COVER_ART)) {
          tag.addField(tag.createField(key, key.name() + "_value"));
        }
      }
      f.commit();

      // Reread File
      f = AudioFileIO.read(testFile);
      tag = f.getTag();

      TagField tf = tag.getFirstField(AsfFieldKey.ALBUM.getFieldName());
      assertEquals("WM/AlbumTitle", tf.getId());
      assertEquals("ALBUM_value", ((TagTextField) tf).getContent());
      assertEquals("UTF-16LE", ((TagTextField) tf).getEncoding());

      tf = tag.getFirstField(AsfFieldKey.ALBUM_ARTIST.getFieldName());
      assertEquals("WM/AlbumArtist", tf.getId());
      assertEquals("ALBUM_ARTIST_value", ((TagTextField) tf).getContent());
      assertEquals("UTF-16LE", ((TagTextField) tf).getEncoding());

      tf = tag.getFirstField(AsfFieldKey.AMAZON_ID.getFieldName());
      assertEquals("ASIN", tf.getId());
      assertEquals("AMAZON_ID_value", ((TagTextField) tf).getContent());
      assertEquals("UTF-16LE", ((TagTextField) tf).getEncoding());

      tf = tag.getFirstField(AsfFieldKey.TITLE.getFieldName());
      assertEquals("TITLE", tf.getId());
      assertEquals("TITLE_value", ((TagTextField) tf).getContent());
      assertEquals("UTF-16LE", ((TagTextField) tf).getEncoding());

    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }
    assertNull(exceptionCaught);
  }
  /** Just create fields for all the tag field keys defined, se if we hit any problems */
  public void testTagFieldKeyWrite() {
    Exception exceptionCaught = null;
    try {
      File testFile = AbstractTestCase.copyAudioToTmp("test1.wma", new File("testwrite1.wma"));

      AudioFile f = AudioFileIO.read(testFile);
      AudioFileIO.delete(f);

      // Tests multiple iterations on same file
      for (int i = 0; i < 2; i++) {
        f = AudioFileIO.read(testFile);
        Tag tag = f.getTag();
        for (FieldKey key : FieldKey.values()) {
          if (!(key == FieldKey.COVER_ART)) {
            tag.setField(tag.createField(key, key.name() + "_value_" + i));
          }
        }
        f.commit();
        f = AudioFileIO.read(testFile);
        tag = f.getTag();
        for (FieldKey key : FieldKey.values()) {
          /*
           * Test value retrieval, using multiple access methods.
           */
          if (!(key == FieldKey.COVER_ART)) {
            String value = key.name() + "_value_" + i;
            System.out.println("Value is:" + value);

            assertEquals(value, tag.getFirst(key));
            AsfTagTextField atf = (AsfTagTextField) tag.getFields(key).get(0);
            assertEquals(value, atf.getContent());
            atf = (AsfTagTextField) tag.getFields(key).get(0);
            assertEquals(value, atf.getContent());
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }
    assertNull(exceptionCaught);
  }
  public MetadataHelper(File f, Boolean debug)
      throws CannotReadException, IOException, TagException, ReadOnlyFileException,
          InvalidAudioFrameException {
    audioFile = AudioFileIO.read(f);

    tag = audioFile.getTag();
    audioHeader = audioFile.getAudioHeader();

    fillMetaInfo();
    fillHeaderInfo();

    if (debug) {
      printResults();
    }
  }
Esempio n. 8
0
  public pfItem(
      File mp3File, String link, String downloadPath, String description, String category) {
    if (pubDate == null) pubDate = new Date();

    _itemID = itemCount;
    itemCount++;
    try {
      AudioFile f = AudioFileIO.read(mp3File);
      Tag tag = f.getTag();

      _title = tag.getFirst(FieldKey.TITLE);
      if (_title == null || _title.trim().length() == 0) {
        _title = mp3File.getName();
      }

      String strTrackNum = tag.getFirst(FieldKey.TRACK);
      if (strTrackNum == null || strTrackNum.trim().length() == 0) {
        _trackNumber = _itemID;
      } else {
        try {
          _trackNumber = Integer.parseInt(strTrackNum);
        } catch (NumberFormatException ex) {
          _trackNumber = _itemID;
        }
      }
    } catch (CannotReadException ex) {
      Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TagException ex) {
      Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ReadOnlyFileException ex) {
      Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAudioFrameException ex) {
      Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex);
    }

    _link = link;
    _description = description;
    _length = mp3File.length();
    _category = category;

    try {
      _guid = (downloadPath + URLEncoder.encode(mp3File.getName(), "UTF-8")).replace("+", "%20");
    } catch (UnsupportedEncodingException ex) {
      Logger.getLogger(pfItem.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Esempio n. 9
0
  /**
   * Fetches all the tags from the local music file: - Artist - Album - Title - Genre
   *
   * @return Song filled with tags
   * @throws InvalidAudioFrameException
   * @throws ReadOnlyFileException
   * @throws CannotReadException
   * @throws TagException
   * @throws IOException
   */
  public Song getSongTags()
      throws CannotReadException, IOException, TagException, ReadOnlyFileException,
          InvalidAudioFrameException {
    // create song
    Song song = new Song();

    // instantiate audio file
    AudioFile audio = AudioFileIO.read(this.songFile);

    Tag tag = audio.getTag();
    song.setArtist(tag.getFirst(FieldKey.ARTIST));
    song.setAlbum(tag.getFirst(FieldKey.ALBUM));
    song.setTitle(tag.getFirst(FieldKey.TITLE));
    song.setGenre(tag.getFirst(FieldKey.GENRE));

    return song;
  }
Esempio n. 10
0
  /** Test reading/writing artwork to Ogg */
  public void testReadWriteArtworkFieldsToOggVorbis() {

    File testFile = null;
    Exception exceptionCaught = null;
    try {
      testFile = AbstractTestCase.copyAudioToTmp("test3.ogg");

      // Read File okay
      AudioFile af = AudioFileIO.read(testFile);
      Tag tag = af.getTag();
      tag.createField(FieldKey.COVER_ART, "test");
    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }
    assertNull(exceptionCaught);
  }
Esempio n. 11
0
  /** Test reading/writing artwork to Flac */
  public void testReadWriteArtworkFieldsToFlac() {
    File testFile = null;
    Exception exceptionCaught = null;
    try {
      testFile = AbstractTestCase.copyAudioToTmp("test.flac");

      // Read File okay
      AudioFile af = AudioFileIO.read(testFile);
      Tag tag = af.getTag();
      tag.createField(FieldKey.COVER_ART, "test");
    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }
    assertNotNull(exceptionCaught);
    assertTrue(exceptionCaught instanceof UnsupportedOperationException);
  }
  /**
   * Shouldnt fail just ecause header size doesnt match file size because file plays ok in winamp
   */
  public void testReadFileWithHeaderSizeDoesntMatchFileSize() {
    File orig = new File("testdata", "test3.wma");
    if (!orig.isFile()) {
      System.err.println("Unable to test file - not available");
      return;
    }

    Exception exceptionCaught = null;
    try {
      File testFile = AbstractTestCase.copyAudioToTmp("test3.wma");
      AudioFile f = AudioFileIO.read(testFile);
      assertEquals("Glass", f.getTag().getFirst(FieldKey.TITLE));
      // Now
    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }
    assertNull(exceptionCaught);
  }
Esempio n. 13
0
 private void insertMusicMetadata() throws IOException {
   atts.reset();
   System.out.format("Extracting music metadata from %s.\n", src.path());
   Tag tags = audio.getTag();
   AudioHeader header = audio.getAudioHeader();
   insert(FORMAT, header.getFormat());
   insert(ENCODINGTYPE, header.getEncodingType());
   insert(BITRATE, header.getBitRate());
   insert(SAMPLERATE, header.getSampleRate());
   insert(LENGTH, header.getTrackLength());
   insert(ALBUM, tags.getFirst(FieldKey.ALBUM));
   insert(ALBUMARTIST, tags.getFirst(FieldKey.ALBUM_ARTIST));
   insert(ARTIST, tags.getFirst(FieldKey.ARTIST));
   insert(TITLE, tags.getFirst(FieldKey.TITLE));
   insert(TRACKNR, tags.getFirst(FieldKey.TRACK));
   insert(DISCNR, tags.getFirst(FieldKey.DISC_NO));
   insert(YEAR, tags.getFirst(FieldKey.YEAR));
   insert(COMMENT, tags.getFirst(FieldKey.COMMENT));
 }
  public String getSongTitle(String songFilePath) {

    String songTitle = "Title";

    // Try to get the song title from the ID3 tag.
    File songFile = new File(songFilePath);
    AudioFile audioFile = null;
    Tag tag = null;
    try {
      audioFile = AudioFileIO.read(songFile);
    } catch (CannotReadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TagException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ReadOnlyFileException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidAudioFrameException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    tag = audioFile.getTag();
    songTitle = tag.getFirst(FieldKey.TITLE);

    // If the ID3 tag doesn't give us the info we need, just use the file name.
    if (songTitle.equals("Title") || songTitle.isEmpty()) {
      int indexOfLastSlash = songTitle.lastIndexOf("/") + 1;
      int indexOfLastDot = songTitle.lastIndexOf(".");
      songTitle = songTitle.substring(indexOfLastSlash, indexOfLastDot);
    }

    return songTitle;
  }
Esempio n. 15
0
  @Override
  public BufferedImage getArtwork() {
    BufferedImage image = super.getArtwork();

    if (image == null) {
      try {
        AudioFile audioFile = AudioFileIO.read(file);
        FlacTag tag = (FlacTag) audioFile.getTag();
        if (tag != null) {
          List<MetadataBlockDataPicture> images = tag.getImages();
          if (images != null && !images.isEmpty()) {
            MetadataBlockDataPicture picture = images.get(0);
            byte[] data = picture.getImageData();
            image = imageFromData(data);
          }
        }
      } catch (Throwable e) {
        LOG.error("Unable to read cover art from flac");
      }
    }

    return image;
  }
 /**
  * writes bpm and key to KEY_START and BPM fields in the tag
  *
  * @param filename
  * @param formattedBpm
  * @param key
  */
 public boolean updateTags(String filename, String formattedBpm, String key) {
   File file = new File(filename);
   try {
     AudioFile f = AudioFileIO.read(file);
     if (!setCustomTag(f, "KEY_START", key)) {
       throw new IOException("Error writing Key Tag");
     }
     if (!c.noBpm) {
       Tag tag = f.getTag();
       if (tag instanceof Mp4Tag) {
         if (!setCustomTag(f, "BPM", formattedBpm)) {
           throw new IOException("Error writing BPM Tag");
         }
       }
       tag.setField(FieldKey.BPM, formattedBpm);
     }
     f.commit();
     return true;
   } catch (Exception e) {
     System.out.println("problem with tags in file " + filename);
     return false;
   }
 }
Esempio n. 17
0
  /**
   * Create a new MusicFile objecy
   *
   * @param musicFile - source music file
   * @param documentsPath - default documents folder for the user
   */
  public MusicFile(File musicFile, String documentsPath) {

    // Set the music file and documents path
    this.musicFile = musicFile;
    this.documentsPath = documentsPath;

    // Determine the absolute path for the source music file
    absolutePath = musicFile.getAbsolutePath();

    // Retreive the file extension from the absolute path
    fileExtension = FilenameUtils.getExtension(absolutePath);

    // If this is a valid music file, retrieve the Tag, and copy the file to
    // the destination
    if (fileExtension.equals("mp3") || fileExtension.equals("m4a") || fileExtension.equals("m4p")) {
      try {
        AudioFile audioF = AudioFileIO.read(this.musicFile);
        musicFileTag = audioF.getTag();

        // Set the artist, album, and song titles
        error = setAttributes();

        // Set the destination file
        if (!error) constructDestination();
      } catch (Exception e) {
        error = true;
        errorMessage = "unidentified error.";
      }

      // Else, this is not a valid music file, set the error flag and
      // error message
    } else {
      errorMessage = "not a valid music file.";
      error = true;
    }
  }
  /**
   * Nimmt die aktuell in <code>tags</code> vorhandenen Metatags, und befŸllt die Editorfelder
   * dementsprechend, dass diese bearbeitet werden kšnne.<br>
   * Hierbei ist das bearbeiten eines einzelnen {@link Tag}s als auch das bearbeiten von mehreren
   * mšglich.
   *
   * @see #editTag(Tag)
   * @see #editTags(ArrayList)
   */
  private void updateEditorControls() {
    watchComponentsForChange = false;

    /* Felder zurücksetzen: */
    editorChanged = false;
    ((EditorComboBoxModel) comTitle.getModel()).reset();
    ((EditorComboBoxModel) comArtist.getModel()).reset();
    ((EditorComboBoxModel) comAlbum.getModel()).reset();
    ((EditorComboBoxModel) comGenre.getModel()).reset();
    txtTracknumber.setText("");
    txtTotalTracks.setText("");
    txtDiscnumber.setText("");
    txtTotalDiscs.setText("");
    txtYear.setText("");
    imgArtwork.setArtwork(null);
    imgArtwork.setChanged(false);

    if (audioFiles == null || audioFiles.size() == 0) {
      setEditorEnabled(false);
    } else {
      setEditorEnabled(true);

      if (audioFiles.size() == 1) {
        // SingleFile-Editing
        AudioFile audioFile = audioFiles.get(0);
        Tag tag = audioFile.getTag();

        /* Felder aktualisieren: */
        comTitle.addItem(tag.getFirstTitle());
        comTitle.setSelectedIndex(comTitle.getItemCount() - 1);
        comArtist.addItem(tag.getFirstArtist());
        comArtist.setSelectedIndex(comArtist.getItemCount() - 1);
        comAlbum.addItem(tag.getFirstAlbum());
        comAlbum.setSelectedIndex(comAlbum.getItemCount() - 1);

        String[] numberBuffer = splitNumberData(tag.getFirstTrack());
        txtTracknumber.setText(numberBuffer[0]);
        txtTracknumber.setEnabled(true);
        txtTotalTracks.setText(numberBuffer[1]);
        numberBuffer = splitNumberData(tag.getFirst(TagFieldKey.DISC_NO));
        txtDiscnumber.setText(numberBuffer[0]);
        txtTotalDiscs.setText(numberBuffer[1]);

        txtYear.setText(tag.getFirstYear());

        EditorComboBoxModel model = (EditorComboBoxModel) comGenre.getModel();
        String genre = tag.getFirstGenre();
        model.addIfNotExists(genre);
        comGenre.setSelectedItem(genre);

        try {
          Artwork artwork = tag.getFirstArtwork();
          BufferedImage cover = null;
          if (artwork != null)
            cover = ImageIO.read(new ByteArrayInputStream(artwork.getBinaryData()));
          imgArtwork.setArtwork(cover);
          imgArtwork.setChanged(false);
        } catch (Exception e) {
          e.printStackTrace();
        }

      } else {
        /* MutliFile-Editing: */
        // ComboBoxes befŸllen:
        // Wenn mehrere Audiodateien gewŠhlt sind, ist es meistens auch der
        // Fall, dass beispielsweise die verschiedenen Files einen verschiedenen
        // Album-Tag haben. Damit der User nicht "von null" ein Album eingeben
        // muss, hat er die Mšglichkeit, zwischen den bereits vorhandenen Varianten
        // eine auszusuchen.
        EditorComboBoxModel model = null;

        String totalTracks = "-1";
        String discnumber = "-1";
        String totalDiscs = "-1";
        for (AudioFile audioFile : audioFiles) {
          Tag tag = audioFile.getTag();

          // Title:
          model = (EditorComboBoxModel) comTitle.getModel();
          model.addIfNotExists(tag.getFirstTitle());

          // Artists:
          model = (EditorComboBoxModel) comArtist.getModel();
          model.addIfNotExists(tag.getFirstArtist());

          // Albums:
          model = (EditorComboBoxModel) comAlbum.getModel();
          model.addIfNotExists(tag.getFirstAlbum());

          // Genre.
          model = (EditorComboBoxModel) comGenre.getModel();
          model.addIfNotExists(tag.getFirstGenre());

          // Total Tracks:
          String[] splitBuffer = splitNumberData(tag.getFirstTrack());
          if (totalTracks.equals("-1") || totalTracks.equals(splitBuffer[1])) {
            totalTracks = splitBuffer[1];
          } else {
            totalTracks = "";
          }

          // Discs:
          splitBuffer = splitNumberData(tag.getFirst(TagFieldKey.DISC_NO));
          if (discnumber.equals("-1") || discnumber.equals(splitBuffer[0])) {
            discnumber = splitBuffer[0];
          } else {
            discnumber = "";
          }

          // Total Discs:
          if (totalDiscs.equals("-1") || totalDiscs.equals(splitBuffer[1])) {
            totalDiscs = splitBuffer[1];
          } else {
            totalDiscs = "";
          }
        }

        txtTracknumber.setText("");
        txtTracknumber.setEnabled(false);
        txtTotalTracks.setText(totalTracks);
        txtDiscnumber.setText(discnumber);
        txtTotalDiscs.setText(totalDiscs);
      }
    }

    watchComponentsForChange = true;
  }
  /**
   * File metadata was set with Media Monkey 3
   *
   * <p>Checking our fields match the fields used by media Monkey 3 (Defacto Standard) by ensuring
   * we can read fields written in Media Monkey
   */
  public void testReadFileFromMediaMonkey3() {
    Exception exceptionCaught = null;
    try {
      File testFile = AbstractTestCase.copyAudioToTmp("test1.wma");
      AudioFile f = AudioFileIO.read(testFile);

      assertEquals("32", f.getAudioHeader().getBitRate());
      assertEquals(
          "ASF (audio): 0x0161 (Windows Media Audio (ver 7,8,9))",
          f.getAudioHeader().getEncodingType());
      assertEquals("2", f.getAudioHeader().getChannels());
      assertEquals("32000", f.getAudioHeader().getSampleRate());
      assertFalse(f.getAudioHeader().isVariableBitRate());

      assertTrue(f.getTag() instanceof AsfTag);
      AsfTag tag = (AsfTag) f.getTag();
      System.out.println(tag);

      // Ease of use methods for common fields
      assertEquals("artist", tag.getFirst(FieldKey.ARTIST));
      assertEquals("album", tag.getFirst(FieldKey.ALBUM));
      assertEquals("tracktitle", tag.getFirst(FieldKey.TITLE));
      assertEquals("comments", tag.getFirst(FieldKey.COMMENT));
      assertEquals("1971", tag.getFirst(FieldKey.YEAR));
      assertEquals("3", tag.getFirst(FieldKey.TRACK));
      assertEquals("genre", tag.getFirst(FieldKey.GENRE));

      assertEquals("artist", tag.getFirst(FieldKey.ARTIST));
      assertEquals("artist", tag.getFirst(AsfFieldKey.AUTHOR.getFieldName()));

      assertEquals("album", tag.getFirst(FieldKey.ALBUM));
      assertEquals("album", tag.getFirst(AsfFieldKey.ALBUM.getFieldName()));

      assertEquals("tracktitle", tag.getFirst(FieldKey.TITLE));
      assertEquals("tracktitle", tag.getFirst(AsfFieldKey.TITLE.getFieldName()));

      assertEquals("genre", tag.getFirst(FieldKey.GENRE));
      assertEquals("genre", tag.getFirst(AsfFieldKey.GENRE.getFieldName()));

      assertEquals("3", tag.getFirst(FieldKey.TRACK));
      assertEquals("1971", tag.getFirst(FieldKey.YEAR));
      assertEquals("genre", tag.getFirst(FieldKey.GENRE));
      assertEquals("comments", tag.getFirst(FieldKey.COMMENT));
      assertEquals("albumartist", tag.getFirst(FieldKey.ALBUM_ARTIST));
      assertEquals("composer", tag.getFirst(FieldKey.COMPOSER));
      assertEquals("grouping", tag.getFirst(FieldKey.GROUPING));
      assertEquals("2", tag.getFirst(FieldKey.DISC_NO));
      assertEquals("lyrics for song", tag.getFirst(FieldKey.LYRICS));

      assertEquals("encoder", tag.getFirst(FieldKey.ENCODER));
      assertEquals("isrc", tag.getFirst(FieldKey.ISRC));

      assertEquals("publisher", tag.getFirst(FieldKey.RECORD_LABEL));
      assertEquals("Lyricist", tag.getFirst(FieldKey.LYRICIST));
      assertEquals("conductor", tag.getFirst(FieldKey.CONDUCTOR));

      assertEquals("Mellow", tag.getFirst(FieldKey.MOOD));

      // Media Monkey does not currently support these fields ...
      // assertEquals("is_compilation", tag.getFirst(FieldKey.IS_COMPILATION));
      // assertEquals("artist_sort", tag.getFirst(FieldKey.ARTIST_SORT));
      // assertEquals("album_artist_sort", tag.getFirst(FieldKey.ALBUM_ARTIST_SORT));
      // assertEquals("album_sort", tag.getFirst(FieldKey.ALBUM_SORT));
      // assertEquals("title_sort", tag.getFirst(FieldKey.TITLE_SORT));
      // assertEquals("barcode", tag.getFirst(FieldKey.BARCODE));
      // assertEquals("catalogno", tag.getFirst(FieldKey.CATALOG_NO));
      // assertEquals("media", tag.getFirst(FieldKey.MEDIA));
      // assertEquals("remixer", tag.getFirst(FieldKey.REMIXER));
      // Now
    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }
    assertNull(exceptionCaught);
  }
  public void testReadFileWithJpgArtwork() {
    File orig = new File("testdata", "test6.wma");
    if (!orig.isFile()) {
      System.err.println("Unable to test file - not available");
      return;
    }

    Exception exceptionCaught = null;
    try {
      File testFile = AbstractTestCase.copyAudioToTmp("test6.wma");
      AudioFile f = AudioFileIO.read(testFile);
      Tag tag = f.getTag();
      assertEquals(1, tag.getFields(FieldKey.COVER_ART).size());

      TagField tagField = tag.getFields(FieldKey.COVER_ART).get(0);
      assertEquals("WM/Picture", tagField.getId());
      assertEquals(5093, tagField.getRawContent().length);

      // Should have been loaded as special field to make things easier
      assertTrue(tagField instanceof AsfTagCoverField);
      AsfTagCoverField coverartField = (AsfTagCoverField) tagField;
      assertEquals("image/jpeg", coverartField.getMimeType());
      assertEquals("coveerart", coverartField.getDescription());
      assertEquals(3, coverartField.getPictureType());
      assertEquals(200, coverartField.getImage().getWidth());
      assertEquals(200, coverartField.getImage().getHeight());
      assertEquals(5093, coverartField.getRawContent().length);
      assertEquals(5046, coverartField.getRawImageData().length);
      assertEquals(5046, coverartField.getImageDataSize());
      assertEquals(coverartField.getRawImageData().length, coverartField.getImageDataSize());

      assertEquals(BufferedImage.TYPE_3BYTE_BGR, coverartField.getImage().getType());

      /** *** TO SOME MANUAL CHECKING **************** */

      // First byte of data is immediatley after the 2 byte Descriptor value
      assertEquals(0x03, tagField.getRawContent()[0]);
      // Raw Data consists of Unknown/MimeType/Name and Actual Image, null seperated  (two bytes)

      // Skip first three unknown bytes plus two byte nulls
      int count = 5;
      String mimeType = null;
      String name = null;
      int endOfMimeType = 0;
      int endOfName = 0;
      while (count < tagField.getRawContent().length - 1) {
        if (tagField.getRawContent()[count] == 0 && tagField.getRawContent()[count + 1] == 0) {
          if (mimeType == null) {
            mimeType = new String(tagField.getRawContent(), 5, (count) - 5, "UTF-16LE");
            endOfMimeType = count + 2;
          } else if (name == null) {
            name =
                new String(
                    tagField.getRawContent(), endOfMimeType, count - endOfMimeType, "UTF-16LE");
            endOfName = count + 2;
            break;
          }
          count += 2;
        }
        count += 2; // keep on two byte word boundary
      }

      assertEquals("image/jpeg", mimeType);
      assertEquals("coveerart", name);

      BufferedImage bi =
          ImageIO.read(
              ImageIO.createImageInputStream(
                  new ByteArrayInputStream(
                      tagField.getRawContent(),
                      endOfName,
                      tagField.getRawContent().length - endOfName)));
      assertNotNull(bi);
      assertEquals(200, bi.getWidth());
      assertEquals(200, bi.getHeight());
      assertEquals(BufferedImage.TYPE_3BYTE_BGR, bi.getType());

    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }
    assertNull(exceptionCaught);
  }
  // TODO Creates temp file in same folder as the original file, this is safe but would impose a
  // performance
  // overhead if the original file is on a networked drive
  public synchronized void write(AudioFile af) throws CannotWriteException {
    logger.info("Started writing tag data for file:" + af.getFile().getName());

    // Prechecks
    precheckWrite(af);

    RandomAccessFile raf = null;
    RandomAccessFile rafTemp = null;
    File newFile = null;
    File result = null;

    // Create temporary File
    try {
      newFile =
          File.createTempFile(
              af.getFile().getName().replace('.', '_'),
              TEMP_FILENAME_SUFFIX,
              af.getFile().getParentFile());
    }
    // Unable to create temporary file, can happen in Vista if have Create Files/Write Data set to
    // Deny
    catch (IOException ioe) {
      logger.log(
          Level.SEVERE,
          ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(
              af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath()),
          ioe);
      throw new CannotWriteException(
          ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(
              af.getFile().getName(), af.getFile().getParentFile().getAbsolutePath()));
    }

    // Open temporary file and actual file for Editing
    try {
      rafTemp = new RandomAccessFile(newFile, WRITE_MODE);
      raf = new RandomAccessFile(af.getFile(), WRITE_MODE);

    }
    // Unable to write to writable file, can happen in Vista if have Create Folders/Append Data set
    // to Deny
    catch (IOException ioe) {
      logger.log(
          Level.SEVERE,
          ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(
              af.getFile().getAbsolutePath()),
          ioe);

      // If we managed to open either file, delete it.
      try {
        if (raf != null) {
          raf.close();
        }
        if (rafTemp != null) {
          rafTemp.close();
        }
      } catch (IOException ioe2) {
        // Warn but assume has worked okay
        logger.log(
            Level.WARNING,
            ErrorMessage.GENERAL_WRITE_PROBLEM_CLOSING_FILE_HANDLE.getMsg(
                af.getFile(), ioe.getMessage()),
            ioe2);
      }

      // Delete the temp file ( we cannot delet until closed correpsonding rafTemp)
      if (!newFile.delete()) {
        // Non critical failed deletion
        logger.warning(
            ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(
                newFile.getAbsolutePath()));
      }

      throw new CannotWriteException(
          ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(
              af.getFile().getAbsolutePath()));
    }

    // Write data to File
    try {

      raf.seek(0);
      rafTemp.seek(0);
      try {
        if (this.modificationListener != null) {
          this.modificationListener.fileWillBeModified(af, false);
        }
        writeTag(af.getTag(), raf, rafTemp);
        if (this.modificationListener != null) {
          this.modificationListener.fileModified(af, newFile);
        }
      } catch (ModifyVetoException veto) {
        throw new CannotWriteException(veto);
      }
    } catch (Exception e) {
      logger.log(
          Level.SEVERE,
          ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(af.getFile(), e.getMessage()),
          e);

      try {
        if (raf != null) {
          raf.close();
        }
        if (rafTemp != null) {
          rafTemp.close();
        }
      } catch (IOException ioe) {
        // Warn but assume has worked okay
        logger.log(
            Level.WARNING,
            ErrorMessage.GENERAL_WRITE_PROBLEM_CLOSING_FILE_HANDLE.getMsg(
                af.getFile().getAbsolutePath(), ioe.getMessage()),
            ioe);
      }

      // Delete the temporary file because either it was never used so lets just tidy up or we did
      // start writing to it but
      // the write failed and we havent renamed it back to the original file so we can just delete
      // it.
      if (!newFile.delete()) {
        // Non critical failed deletion
        logger.warning(
            ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(
                newFile.getAbsolutePath()));
      }
      throw new CannotWriteException(
          ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(af.getFile(), e.getMessage()));
    } finally {
      try {
        if (raf != null) {
          raf.close();
        }
        if (rafTemp != null) {
          rafTemp.close();
        }
      } catch (IOException ioe) {
        // Warn but assume has worked okay
        logger.log(
            Level.WARNING,
            ErrorMessage.GENERAL_WRITE_PROBLEM_CLOSING_FILE_HANDLE.getMsg(
                af.getFile().getAbsolutePath(), ioe.getMessage()),
            ioe);
      }
    }

    // Result held in this file
    result = af.getFile();

    // If the temporary file was used
    if (newFile.length() > 0) {
      // Rename Original File
      // Can fail on Vista if have Special Permission 'Delete' set Deny
      File originalFileBackup =
          new File(
              af.getFile().getParentFile().getPath(),
              AudioFile.getBaseFilename(af.getFile()) + ".old");
      boolean renameResult = af.getFile().renameTo(originalFileBackup);
      if (renameResult == false) {
        logger.log(
            Level.SEVERE,
            ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_FILE_TO_BACKUP.getMsg(
                af.getFile().getPath(), originalFileBackup.getName()));
        throw new CannotWriteException(
            ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_FILE_TO_BACKUP.getMsg(
                af.getFile().getPath(), originalFileBackup.getName()));
      }

      // Rename Temp File to Original File
      renameResult = newFile.renameTo(af.getFile());
      if (!renameResult) {
        // Renamed failed so lets do some checks rename the backup back to the original file
        // New File doesnt exist
        if (!newFile.exists()) {
          logger.warning(
              ErrorMessage.GENERAL_WRITE_FAILED_NEW_FILE_DOESNT_EXIST.getMsg(
                  newFile.getAbsolutePath()));
        }

        // Rename the backup back to the original
        if (!originalFileBackup.renameTo(af.getFile())) {
          // TODO now if this happens we are left with testfile.old instead of testfile.mp4
          logger.warning(
              ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_ORIGINAL_BACKUP_TO_ORIGINAL.getMsg(
                  originalFileBackup.getAbsolutePath(), af.getFile().getName()));
        }

        logger.warning(
            ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_TO_ORIGINAL_FILE.getMsg(
                af.getFile().getAbsolutePath(), newFile.getName()));
        throw new CannotWriteException(
            ErrorMessage.GENERAL_WRITE_FAILED_TO_RENAME_TO_ORIGINAL_FILE.getMsg(
                af.getFile().getAbsolutePath(), newFile.getName()));
      } else {
        // Rename was okay so we can now delete the backup of the original
        boolean deleteResult = originalFileBackup.delete();
        if (!deleteResult) {
          // Not a disaster but can't delete the backup so make a warning
          logger.warning(
              ErrorMessage.GENERAL_WRITE_WARNING_UNABLE_TO_DELETE_BACKUP_FILE.getMsg(
                  originalFileBackup.getAbsolutePath()));
        }
      }

      // Delete the temporary file if still exists
      if (newFile.exists()) {
        if (!newFile.delete()) {
          // Non critical failed deletion
          logger.warning(
              ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(newFile.getPath()));
        }
      }
    } else {
      // Delete the temporary file that wasn't ever used
      if (!newFile.delete()) {
        // Non critical failed deletion
        logger.warning(
            ErrorMessage.GENERAL_WRITE_FAILED_TO_DELETE_TEMPORARY_FILE.getMsg(newFile.getPath()));
      }
    }

    if (this.modificationListener != null) {
      this.modificationListener.fileOperationFinished(result);
    }
  }
  /**
   * This will write a custom ID3 tag (TXXX). This works only with MP3 files (Flac with ID3-Tag not
   * tested).
   *
   * @param description The description of the custom tag i.e. "catalognr" There can only be one
   *     custom TXXX tag with that description in one MP3 file
   * @param text The actual text to be written into the new tag field
   * @return True if the tag has been properly written, false otherwise
   */
  public static boolean setCustomTag(AudioFile audioFile, String description, String text)
      throws IOException {
    FrameBodyTXXX txxxBody = new FrameBodyTXXX();
    txxxBody.setDescription(description);
    txxxBody.setText(text);

    // Get the tag from the audio file
    // If there is no ID3Tag create an ID3v2.3 tag
    Tag tag = audioFile.getTagOrCreateAndSetDefault();
    if (tag instanceof AbstractID3Tag) {
      // If there is only a ID3v1 tag, copy data into new ID3v2.3 tag
      if (!(tag instanceof ID3v23Tag || tag instanceof ID3v24Tag)) {
        Tag newTagV23 = null;
        if (tag instanceof ID3v1Tag) {
          newTagV23 =
              new ID3v23Tag((ID3v1Tag) audioFile.getTag()); // Copy old tag data
        }
        if (tag instanceof ID3v22Tag) {
          newTagV23 =
              new ID3v23Tag((ID3v22Tag) audioFile.getTag()); // Copy old tag data
        }
        audioFile.setTag(newTagV23);
        tag = newTagV23;
      }

      AbstractID3v2Frame frame = null;
      if (tag instanceof ID3v23Tag) {
        if (((ID3v23Tag) audioFile.getTag()).getInvalidFrames() > 0) {
          throw new IOException("read some invalid frames!");
        }
        frame = new ID3v23Frame("TXXX");
      } else if (tag instanceof ID3v24Tag) {
        if (((ID3v24Tag) audioFile.getTag()).getInvalidFrames() > 0) {
          throw new IOException("read some invalid frames!");
        }
        frame = new ID3v24Frame("TXXX");
      }

      frame.setBody(txxxBody);

      try {
        tag.setField(frame);
      } catch (FieldDataInvalidException e) {
        Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, e);
        return false;
      }
    } else if (tag instanceof FlacTag) {
      try {
        ((FlacTag) tag).setField(description, text);
      } catch (KeyNotFoundException ex) {
        Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
      } catch (FieldDataInvalidException ex) {
        return false;
      }
    } else if (tag instanceof Mp4Tag) {
      // TagField field = new Mp4TagTextField("----:com.apple.iTunes:"+description, text);
      TagField field;
      field =
          new Mp4TagReverseDnsField(
              Mp4TagReverseDnsField.IDENTIFIER + ":" + "com.apple.iTunes" + ":" + description,
              "com.apple.iTunes",
              description,
              text);
      // TagField field = new Mp4TagTextField(description, text);
      try {
        tag.setField(field);
      } catch (FieldDataInvalidException ex) {
        Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
      }
    } else if (tag instanceof VorbisCommentTag) {
      try {
        ((VorbisCommentTag) tag).setField(description, text);
      } catch (KeyNotFoundException ex) {
        Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
      } catch (FieldDataInvalidException ex) {
        Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
      }
    } else {
      // tag not implented
      Logger.getLogger(TrackAnalyzer.class.getName())
          .log(
              Level.WARNING,
              "couldn't write key information for "
                  + audioFile.getFile().getName()
                  + " to tag, because this format is not supported.");
      return false;
    }

    // write changes in tag to file
    try {
      audioFile.commit();
    } catch (CannotWriteException e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }
Esempio n. 23
0
    @Override
    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
        throws IOException {
      // System.out.println(file + "\t" + Thread.currentThread());
      // addSong(file);
      final File song = file.toFile();
      AudioFile f;
      Logger.getLogger("org.jaudiotagger").setLevel(Level.OFF);
      final String extension = getExtension(song.getPath());
      if (Arrays.asList(types).contains(extension)) {
        final String localUrl =
            "file:///" + AurousStringUtils.htmlEncode(song.getPath().toString().replace("\\", "/"));
        try {

          f = AudioFileIO.read(song);
          final Tag tag = f.getTag();
          if (tag != null) {
            String artist = tag.getFirst(FieldKey.ARTIST);
            String title = tag.getFirst(FieldKey.TITLE);
            String album = tag.getFirst(FieldKey.ALBUM);
            if (StringUtils.isBlank(artist)) {
              artist = "Unknown";
            }
            if (StringUtils.isBlank(title)) {
              title = "Unknown";
            }
            if (StringUtils.isBlank(album)) {
              album = "Unknown";
            }
            final int duration = f.getAudioHeader().getTrackLength();

            final String artworkBase64 = "assets/img/noalbumart.png";
            if (!DatabaseManager.isInCollection(localUrl)) {
              DatabaseManager.addSong(
                  title, artist, album, artworkBase64, duration, localUrl, "null", "null");
              //	System.out.println(localUrl);
            }
          } else {
            final int duration = f.getAudioHeader().getTrackLength();
            if (!DatabaseManager.isInCollection(localUrl)) {
              DatabaseManager.addSong(
                  "Unknown",
                  "Unknown",
                  "Unknown",
                  "assets/img/noalbumart.png",
                  duration,
                  localUrl,
                  "null",
                  "null");
            }
          }
        } catch (CannotReadException
            | IOException
            | TagException
            | ReadOnlyFileException
            | InvalidAudioFrameException e) {
          System.out.println("No headers detected");
          //	ExceptionWidget widget = new ExceptionWidget(e);
          //	widget.showWidget();
        }
      }
      return FileVisitResult.CONTINUE;
    }
  public static boolean generate_audio_info_xml(
      File saveLocation, TOTorrent inTorrent, File metaFile) {

    Map<String, Properties> audio_file_properties = new HashMap<String, Properties>();

    if (inTorrent.isSimpleTorrent()) {
      Properties p = new Properties();
      InOrderType type = InOrderType.getType(saveLocation.getName());
      if (type != null) {

        if (type.getFileTypeFilter().equals(FileTypeFilter.Audio)) {
          try {
            AudioFile f = AudioFileIO.read(saveLocation);
            Tag tag = f.getTag();

            if (tag != null) {
              AudioHeader audioHeader = f.getAudioHeader();
              setPropsFromTagAndHeader(p, audioHeader, tag);
            }

            if (p.size() > 0) {
              audio_file_properties.put(saveLocation.getName(), p);
            }
          } catch (Exception e) {
            System.err.println("audio tag parse error: " + e.toString());
          }
        }
      }
    } else {
      for (TOTorrentFile torrent_file : inTorrent.getFiles()) {
        Properties p = new Properties();
        audio_file_properties.put(torrent_file.getRelativePath(), p);

        InOrderType type = InOrderType.getType(torrent_file.getRelativePath());
        if (type != null) {

          if (type.getFileTypeFilter().equals(FileTypeFilter.Audio)) {
            try {
              File file = new File(saveLocation, torrent_file.getRelativePath());
              AudioFile f = AudioFileIO.read(file);
              Tag tag = f.getTag();

              if (tag != null) {
                AudioHeader audioHeader = f.getAudioHeader();
                setPropsFromTagAndHeader(p, audioHeader, tag);

                if (p.size() > 0) {
                  audio_file_properties.put(saveLocation.getName(), p);
                }
              }
            } catch (Exception e) {
              System.err.println("audio tag parse error: " + e.toString());
            }
          } // if it's an audio type
        } // if this file has a recognizable type
      } // for over torrent files
    }

    if (audio_file_properties.size() > 0) {
      try {
        XMLEncoder encoder =
            new XMLEncoder(new BufferedOutputStream(new FileOutputStream(metaFile)));
        encoder.writeObject(audio_file_properties);
        encoder.close();
        logger.fine(
            "wrote audio properties xml for: " + (new String(inTorrent.getName(), "UTF-8")));
      } catch (Exception e) {
        try {
          logger.warning(
              "error writing audio properties for: "
                  + new String(inTorrent.getName(), "UTF-8")
                  + " / "
                  + e.toString());
        } catch (UnsupportedEncodingException e1) {
          e1.printStackTrace();
        }
        e.printStackTrace();
        return false;
      }

      return true;
    }
    return false;
  }
  public void testWriteFile() {
    Exception exceptionCaught = null;
    try {
      File testFile = AbstractTestCase.copyAudioToTmp("test1.wma", new File("testwrite1.wma"));
      AudioFile f = AudioFileIO.read(testFile);

      assertEquals("32", f.getAudioHeader().getBitRate());
      assertEquals(
          "ASF (audio): 0x0161 (Windows Media Audio (ver 7,8,9))",
          f.getAudioHeader().getEncodingType());
      assertEquals("2", f.getAudioHeader().getChannels());
      assertEquals("32000", f.getAudioHeader().getSampleRate());
      assertFalse(f.getAudioHeader().isVariableBitRate());

      assertTrue(f.getTag() instanceof AsfTag);
      AsfTag tag = (AsfTag) f.getTag();

      // Write some new values and save
      tag.setField(FieldKey.ARTIST, "artist2");
      tag.setField(FieldKey.ALBUM, "album2");
      tag.setField(FieldKey.TITLE, "tracktitle2");
      tag.setField(FieldKey.COMMENT, "comments2");
      tag.addField(FieldKey.YEAR, "1972");
      tag.setField(FieldKey.GENRE, "genre2");
      tag.setField(FieldKey.TRACK, "4");
      tag.setCopyright("copyright");
      tag.setRating("rating");
      tag.setField(tag.createField(FieldKey.URL_LYRICS_SITE, "http://www.lyrics.fly.com"));
      tag.setField(tag.createField(FieldKey.URL_DISCOGS_ARTIST_SITE, "http://www.discogs1.com"));
      tag.setField(tag.createField(FieldKey.URL_DISCOGS_RELEASE_SITE, "http://www.discogs2.com"));
      tag.setField(tag.createField(FieldKey.URL_OFFICIAL_ARTIST_SITE, "http://www.discogs3.com"));
      tag.setField(tag.createField(FieldKey.URL_OFFICIAL_RELEASE_SITE, "http://www.discogs4.com"));
      tag.addField(tag.createField(FieldKey.URL_WIKIPEDIA_ARTIST_SITE, "http://www.discogs5.com"));
      tag.addField(tag.createField(FieldKey.URL_WIKIPEDIA_RELEASE_SITE, "http://www.discogs6.com"));
      tag.setField(tag.createField(FieldKey.DISC_TOTAL, "3"));
      tag.setField(tag.createField(FieldKey.TRACK_TOTAL, "11"));

      // setField the IsVbr value (can be modified for now)
      tag.setField(tag.createField(AsfFieldKey.ISVBR, Boolean.TRUE.toString()));
      f.commit();

      f = AudioFileIO.read(testFile);
      tag = (AsfTag) f.getTag();

      assertTrue(f.getAudioHeader().isVariableBitRate());

      assertEquals("artist2", tag.getFirst(FieldKey.ARTIST));
      assertEquals("album2", tag.getFirst(FieldKey.ALBUM));
      assertEquals("tracktitle2", tag.getFirst(FieldKey.TITLE));
      assertEquals("comments2", tag.getFirst(FieldKey.COMMENT));
      assertEquals("1972", tag.getFirst(FieldKey.YEAR));
      assertEquals("4", tag.getFirst(FieldKey.TRACK));
      assertEquals("genre2", tag.getFirst(FieldKey.GENRE));
      assertEquals("copyright", tag.getFirstCopyright());
      assertEquals("rating", tag.getFirstRating());
      assertEquals("http://www.lyrics.fly.com", tag.getFirst(FieldKey.URL_LYRICS_SITE));
      assertEquals("http://www.discogs1.com", tag.getFirst(FieldKey.URL_DISCOGS_ARTIST_SITE));
      assertEquals("http://www.discogs2.com", tag.getFirst(FieldKey.URL_DISCOGS_RELEASE_SITE));
      assertEquals("http://www.discogs3.com", tag.getFirst(FieldKey.URL_OFFICIAL_ARTIST_SITE));
      assertEquals("http://www.discogs4.com", tag.getFirst(FieldKey.URL_OFFICIAL_RELEASE_SITE));
      assertEquals("http://www.discogs5.com", tag.getFirst(FieldKey.URL_WIKIPEDIA_ARTIST_SITE));
      assertEquals("http://www.discogs6.com", tag.getFirst(FieldKey.URL_WIKIPEDIA_RELEASE_SITE));
      assertEquals("3", tag.getFirst(FieldKey.DISC_TOTAL));
      assertEquals("11", tag.getFirst(FieldKey.TRACK_TOTAL));

      AudioFileIO.delete(f);
      f = AudioFileIO.read(testFile);
      tag = (AsfTag) f.getTag();

      assertFalse(f.getAudioHeader().isVariableBitRate());
      assertTrue(tag.isEmpty());

    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }
    assertNull(exceptionCaught);
  }
Esempio n. 26
0
  private static void setID3(File mp3) {
    // populate Database with id3 tag information
    try {

      // Turn off all logging. This should be moved??

      Logger logger = Logger.getLogger("org.jaudiotagger");

      logger.setLevel(Level.OFF);

      File song = mp3;

      // FileInputStream file = new FileInputStream(song);

      AudioFile f = AudioFileIO.read(song);

      Tag tag = f.getTag();

      System.out.println("Track Length: " + f.getAudioHeader().getTrackLength());

      int bitRate = f.getAudioHeader().getSampleRateAsNumber();

      String artist = tag.getFirstArtist();
      System.out.println("here " + tag.getFirstArtist());
      String album = tag.getFirstAlbum();

      String songTitle = tag.getFirstTitle();

      InsertValues insert1 = new InsertValues();

      insert1.insertInfo(artist, songTitle, bitRate, "Audio_Files");
      // System.out.println(tag.getFirstComment());

      System.out.println("Year: " + tag.getFirstYear());

      // System.out.println(tag.getFirstTrack());

      /*

      * Removed. This is for version 1 only

      *

      * int size = (int)song.length(); file.skip(size - 128); byte[]

      * last128 = new byte[128]; file.read(last128); String id3 = new

      * String(last128); String tag = id3.substring(0, 3); if

      * (tag.equals("TAG")) { System.out.println("Title: " +

      * id3.substring(3, 32)); System.out.println("Artist: " +

      * id3.substring(33, 62)); System.out.println("Album: " +

      * id3.substring(63, 91)); System.out.println("Year: " +

      * id3.substring(93, 97)); } else //System.out.println(mp3 + " does

      * not contain" + " ID3 info.");

      */

      // file.close();

    } catch (Exception e) {

      System.out.println("file read error error message was e = " + e.toString());
    }
  }
  /**
   * File metadata was set with PicardQt
   *
   * <p>Checking our fields match the fields used by picard Qt3 (Defacto Standard for Musicbrainz
   * fields) by ensuring we can read fields written in Picard Qt
   */
  public void testReadFileFromPicardQt() {
    File orig = new File("testdata", "test2.wma");
    if (!orig.isFile()) {
      System.err.println("Unable to test file - not available");
      return;
    }

    Exception exceptionCaught = null;
    try {
      File testFile = AbstractTestCase.copyAudioToTmp("test2.wma");
      AudioFile f = AudioFileIO.read(testFile);

      assertEquals("128", f.getAudioHeader().getBitRate());
      assertEquals(
          "ASF (audio): 0x0162 (Windows Media Audio 9 series (Professional))",
          f.getAudioHeader().getEncodingType());
      assertEquals("2", f.getAudioHeader().getChannels());
      assertEquals("44100", f.getAudioHeader().getSampleRate());
      assertFalse(f.getAudioHeader().isVariableBitRate());

      assertTrue(f.getTag() instanceof AsfTag);
      AsfTag tag = (AsfTag) f.getTag();
      System.out.println(tag);

      // Ease of use methods for common fields
      assertEquals("Sonic Youth", tag.getFirst(FieldKey.ARTIST));
      assertEquals("Sister", tag.getFirst(FieldKey.ALBUM));
      assertEquals("(I Got a) Catholic Block", tag.getFirst(FieldKey.TITLE));
      assertEquals("1987", tag.getFirst(FieldKey.YEAR));
      assertEquals("2", tag.getFirst(FieldKey.TRACK)); // NOTE:track can have seroes or not
      assertEquals("no wave", tag.getFirst(FieldKey.GENRE));

      assertEquals("Sonic Youth", tag.getFirst(FieldKey.ARTIST));

      assertEquals("Sonic Youth", tag.getFirst(AsfFieldKey.AUTHOR.getFieldName()));

      assertEquals("Sister", tag.getFirst(FieldKey.ALBUM));
      assertEquals("Sister", tag.getFirst(AsfFieldKey.ALBUM.getFieldName()));

      assertEquals("(I Got a) Catholic Block", tag.getFirst(FieldKey.TITLE));
      assertEquals("(I Got a) Catholic Block", tag.getFirst(AsfFieldKey.TITLE.getFieldName()));

      assertEquals("no wave", tag.getFirst(FieldKey.GENRE));
      assertEquals("no wave", tag.getFirst(AsfFieldKey.GENRE.getFieldName()));

      assertEquals("2", tag.getFirst(FieldKey.TRACK));
      assertEquals("2", tag.getFirst(AsfFieldKey.TRACK.getFieldName()));

      assertEquals("1987", tag.getFirst(FieldKey.YEAR));
      assertEquals("1987", tag.getFirst(AsfFieldKey.YEAR.getFieldName()));

      assertEquals("Sonic Youth", tag.getFirst(FieldKey.ALBUM_ARTIST));
      assertEquals("Sonic Youth", tag.getFirst(AsfFieldKey.ALBUM_ARTIST.getFieldName()));

      assertEquals("Blast First", tag.getFirst(FieldKey.RECORD_LABEL));
      assertEquals("Blast First", tag.getFirst(AsfFieldKey.RECORD_LABEL.getFieldName()));

      assertEquals("Sonic Youth", tag.getFirst(FieldKey.ARTIST_SORT));
      assertEquals("Sonic Youth", tag.getFirst(AsfFieldKey.ARTIST_SORT.getFieldName()));

      assertEquals("Sonic Youth", tag.getFirst(FieldKey.ARTIST_SORT));
      assertEquals("Sonic Youth", tag.getFirst(AsfFieldKey.ARTIST_SORT.getFieldName()));

      assertEquals("Sonic Youth", tag.getFirst(FieldKey.ALBUM_ARTIST_SORT));
      assertEquals("Sonic Youth", tag.getFirst(AsfFieldKey.ALBUM_ARTIST_SORT.getFieldName()));

      assertEquals("official", tag.getFirst(FieldKey.MUSICBRAINZ_RELEASE_STATUS));
      assertEquals("official", tag.getFirst(AsfFieldKey.MUSICBRAINZ_RELEASE_STATUS.getFieldName()));

      assertEquals("album", tag.getFirst(FieldKey.MUSICBRAINZ_RELEASE_TYPE));
      assertEquals("album", tag.getFirst(AsfFieldKey.MUSICBRAINZ_RELEASE_TYPE.getFieldName()));

      assertEquals("GB", tag.getFirst(FieldKey.MUSICBRAINZ_RELEASE_COUNTRY));
      assertEquals("GB", tag.getFirst(AsfFieldKey.MUSICBRAINZ_RELEASE_COUNTRY.getFieldName()));

      assertEquals(
          "5cbef01b-cc35-4f52-af7b-d0df0c4f61b9",
          tag.getFirst(FieldKey.MUSICBRAINZ_RELEASEARTISTID));
      assertEquals(
          "5cbef01b-cc35-4f52-af7b-d0df0c4f61b9",
          tag.getFirst(AsfFieldKey.MUSICBRAINZ_RELEASEARTISTID.getFieldName()));

      assertEquals(
          "f8ece8ad-0ef1-45c0-9d20-a58a10052d5c", tag.getFirst(FieldKey.MUSICBRAINZ_TRACK_ID));
      assertEquals(
          "f8ece8ad-0ef1-45c0-9d20-a58a10052d5c",
          tag.getFirst(AsfFieldKey.MUSICBRAINZ_TRACK_ID.getFieldName()));

      assertEquals(
          "ca16e36d-fa43-4b49-8c71-d98bd70b341f", tag.getFirst(FieldKey.MUSICBRAINZ_RELEASEID));
      assertEquals(
          "ca16e36d-fa43-4b49-8c71-d98bd70b341f",
          tag.getFirst(AsfFieldKey.MUSICBRAINZ_RELEASEID.getFieldName()));

      assertEquals(
          "5cbef01b-cc35-4f52-af7b-d0df0c4f61b9", tag.getFirst(FieldKey.MUSICBRAINZ_ARTISTID));
      assertEquals(
          "5cbef01b-cc35-4f52-af7b-d0df0c4f61b9",
          tag.getFirst(AsfFieldKey.MUSICBRAINZ_ARTISTID.getFieldName()));

      // This example doesnt populate these fields
      // assertEquals("Sonic Youth", tag.getFirst(FieldKey.COMPOSER));
      // assertEquals("grouping", tag.getFirst(FieldKey.GROUPING));
      // assertEquals("2", tag.getFirst(FieldKey.DISC_NO));
      // assertEquals("lyrics for song", tag.getFirst(FieldKey.LYRICS));
      // assertEquals("encoder", tag.getFirst(FieldKey.ENCODER));
      // assertEquals("isrc", tag.getFirst(FieldKey.ISRC));
      // assertEquals("Lyricist", tag.getFirst(FieldKey.LYRICIST));
      // assertEquals("conductor", tag.getFirst(FieldKey.CONDUCTOR));
      // assertEquals("Mellow", tag.getFirst(FieldKey.INVOLVED_PEOPLE));
      // assertEquals("5cbef01b-cc35-4f52-af7b-d0df0c4f61b9", tag.getFirst(FieldKey.MUSICIP_ID));

      // Picard Qt does not currently support these fields ...
      // assertEquals("is_compilation", tag.getFirst(FieldKey.IS_COMPILATION));
      // assertEquals("album_sort", tag.getFirst(FieldKey.ALBUM_SORT));
      // assertEquals("title_sort", tag.getFirst(FieldKey.TITLE_SORT));
      // assertEquals("barcode", tag.getFirst(FieldKey.BARCODE));
      // assertEquals("catalogno", tag.getFirst(FieldKey.CATALOG_NO));
      // assertEquals("media", tag.getFirst(FieldKey.MEDIA));
      // assertEquals("remixer", tag.getFirst(FieldKey.REMIXER));

      // Now
    } catch (Exception e) {
      e.printStackTrace();
      exceptionCaught = e;
    }
    assertNull(exceptionCaught);
  }