Apache Tika - Extracting MP3 file



Example - Extracting Content and Metadata from a MP3 file

Given below is the program to extract content and metadata from a MP3 file.

TikaDemo.java

package com.tutorialspoint.tika;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.mp3.LyricsHandler;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.apache.tika.sax.BodyContentHandler;

import org.xml.sax.SAXException;

public class TikaDemo {

   public static void main(final String[] args) throws Exception, IOException, SAXException, TikaException {

      //detecting the file type
      BodyContentHandler handler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      FileInputStream inputstream = new FileInputStream(new File("D:/projects/example.mp3"));
      ParseContext pcontext = new ParseContext();
      
      //Mp3 parser
      Mp3Parser  Mp3Parser = new  Mp3Parser();
      Mp3Parser.parse(inputstream, handler, metadata, pcontext);
      LyricsHandler lyrics = new LyricsHandler(inputstream,handler);
      
      while(lyrics.hasLyrics()) {
    	  System.out.println(lyrics.toString());
      }
      
      System.out.println("Contents of the document:" + handler.toString());
      System.out.println("Metadata of the document:");
      String[] metadataNames = metadata.names();

      for(String name : metadataNames) {		        
    	  System.out.println(name + ": " + metadata.get(name));
      }
   }
}

Output

Example.mp3 file has the following properties −

Example MP3

You will get the following output after executing the program. If the given file has any lyrics, our application will capture and display that along with the output.

Contents of the document:null
3.2653103

Metadata of the document:
xmpDM:audioSampleRate: 44100
channels: 2
xmpDM:audioCompressor: MP3
xmpDM:audioChannelType: Stereo
version: MPEG 3 Layer III Version 1
xmpDM:duration: 3.265310287475586
Content-Type: audio/mpeg
samplerate: 44100

Advertisements