Home » Desktop Java » sound » Get Midi audio file properties

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Get Midi audio file properties

With this tutorial we are going to see how to get MIDI audio file properties. This is a useful operation when you want to inform the user about several important properties of the audio files.

Basically in order to get MIDI audio file properties one should follow these steps:

  • Obtain the default Sequencer connected to a default device using MidiSystem.getSequencer().
  • Create a stream from a file to the MIDI file.
  • Use MidiSystem.getMidiFileFormat to obtain the MIDI file format of the data in the specified input stream. This will return you an MidiFileFormat object.

Let’s see the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.sound.midi.MidiFileFormat;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequencer;

public class GetMidiAudioFileProperties {

	public static void main(String[] args) throws Exception {

		// Obtains the default Sequencer connected to a default device.
		Sequencer sequencer = MidiSystem.getSequencer();

	    // create a stream from a file
	    InputStream is = new BufferedInputStream(new FileInputStream(new File("midifile.mid")));

	    // Obtain the MIDI file format of the data in the specified input stream.
	    MidiFileFormat fformat = MidiSystem.getMidiFileFormat(is);

	    // Obtain the MIDI file type.
		switch (fformat.getType()) {
			case 0:
				System.out.println("mid file format");
				break;
			case 1:
				System.out.println("rmf file format");
				break;
		}

	    // Sets the current sequence on which the sequencer operates.
	    // The stream must point to MIDI file data.
	    sequencer.setSequence(is);

	    // Obtains the length of the current sequence, expressed in microseconds
	    long durationMicroSecs = sequencer.getMicrosecondLength();
	    long durationSecs = durationMicroSecs/1000000;

	    System.out.println("durationInSecs " + durationSecs);

	}

}

Output:

rmf file format
durationInSecs 122

 
This was an example on how to get Midi audio file properties.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of