Home » Desktop Java » sound » Play Midi audio

About Ilias Tsagklis

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

Play Midi audio

With this example we shall show you how to play MIDI audio files in a Java Desktop Application. This is very useful when you want to embed a simple audio player in your application.

In short, playing MIDI audio files requires that you:

  • Obtain the default Sequencer connected to a default device using MidiSystem.getSequencer().
  • Create a stream from a file to the MIDI file.
  • Sets the current sequence on which the sequencer operates using sequencer.setSequence.
  • Finally, start playback of the MIDI data in the currently loaded sequence using sequencer.start()

Here is the code:

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.MidiSystem;
import javax.sound.midi.Sequencer;

public class PlayMidiAudio {

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

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

		// Opens the device, indicating that it should now acquire any
	    // system resources it requires and become operational.
		sequencer.open();

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

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

	    // Starts playback of the MIDI data in the currently loaded sequence.
	    sequencer.start();

	}

}

 
This was an example on how to play MIDI audio.

(No Ratings Yet)
1 Comment 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

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Adnan Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Adnan
Guest
Adnan

Hello ! Thanks for the code. But, this doesn’t work for me. When I run this class, it just keeps running in an infinite loop without playing the .mid audio. Can you please let me know where all I can debug the issue.