How to play MIDI files using the Java Sound API

Introduction

This article is a reminder of how to play MIDI files using the Java Sound API. This is a rudimentary article that can be played / stopped for the time being.

Sample code

Here is the sample source code. It's a simple program that plays MIDI when you enter the path of a MIDI file using console input. Please forgive me for the exception handling that is insanely applicable. m (__) m

SamplePlayer.java


import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;

public class SamplePlayer {

	public static void main(String[] args) {
		//Hardware to play MIDI data/An instance of a software device.
		Sequencer sequencer = null;

		try {
			//Get the default Sequencer connected to the device.
			sequencer = MidiSystem.getSequencer();

			//Open the device and acquire resources.
			sequencer.open();
		}
		catch (MidiUnavailableException e) {
			e.printStackTrace();
		}

		//Get the MIDI file path from the console input.
		Scanner scanner = new Scanner(System.in);
		System.out.print("MIDI file path>> ");
		String path = scanner.next();

		try {
			//MIDI data from MIDI files(Sequence object)Get.
			File file = new File(path);
			Sequence sequence = MidiSystem.getSequence(file);

			//Set the acquired MIDI data in the sequencer.
			sequencer.setSequence(sequence);
		}
		catch (InvalidMidiDataException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		//Sequencer playback
		sequencer.start();

		//Waiting for key input
		System.out.println("Enter an appropriate character string to finish.");
		System.out.print(">>");
		scanner.next();
		scanner.close();

		//Sequencer stop
		sequencer.stop();

		//Close the sequencer and release the resources you were using.
		sequencer.close();
	}
}

Commentary

Prepare a sequencer

Gets the objects needed for MIDI playback. The code below will automatically get the default device provided by the API. (If you just want to play it, the default is enough.)

** * [1] and [2] throw "MidiUnavailableException", so be sure to handle the exception. ** **


	Sequencer sequencer = null;
	try {
		// [1]Get the default Sequencer connected to the device.
		sequencer = MidiSystem.getSequencer();

		// [2]Open the device and acquire resources.
		sequencer.open();
	}
	catch (MidiUnavailableException e) {
		e.printStackTrace();
	}

Read MIDI file

Get MIDI data from a MIDI file. The acquired MIDI data is managed by an object called "Sequence".

Set the acquired object in the sequencer.

** * As before, [1] and [2] throw "MidiUnavailableException", so be sure to handle the exception. ** **

	try {
		// [1]MIDI data from MIDI files(Sequence object)Get.
		File file = new File(path);
		Sequence sequence = MidiSystem.getSequence(file);

		// [2]Set the acquired MIDI data in the sequencer.
		sequencer.setSequence(sequence);
	}
	catch (InvalidMidiDataException e) {
		e.printStackTrace();
	}
	catch (IOException e) {
		e.printStackTrace();
	}


MIDI play / stop

After that, you can control play / stop by calling play (start) and stop (stop) of the sequencer.

	//Sequencer playback
	sequencer.start();

	//Sequencer stop
	sequencer.stop();

Release system resources

Be careful not to forget to execute close () at the end of the program.

	sequencer.close();

Recommended Posts

How to play MIDI files using the Java Sound API
How to play MIDI files using the Java Sound API (specify the MIDI device to use)
[Java] How to operate List using Stream API
How to disassemble Java class files
How to decompile java class files
[Java] How to use the File class
[Java] How to use the hasNext function
Try using the Stream API in Java
[Java] How to use the HashMap class
[Java] How to calculate age using LocalDate
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
[Java] How to output and write files!
[Java] How to get the current directory
[Processing × Java] How to use the class
How to install the legacy version [Java]
How to get the date in java
[Java] How to use the Calendar class
[Java] How to get to the front of a specific string using the String class
[Java] How to use Thread.sleep to pause the program
ChatWork4j for using the ChatWork API in Java
How to play audio and music using javascript
How to add sound in the app (swift)
How to implement the breadcrumb function using gretel
How to use Java API with lambda expression
[Java] (for MacOS) How to set the classpath
How to use the replace () method (Java Silver)
[Java] How to get the redirected final URL
Try using the COTOHA API parsing in Java
[Java] Memo on how to write the source
[Java] How to get the authority of the folder
[Java] How to easily get the longest character string of ArrayList using stream
How to set tabs and spaces to be visible by using the tab key to insert spaces in Java files in Eclipse
[Java] How to get the URL of the transition source
[Java] How to omit the private constructor in Lombok
How to write Scala from the perspective of Java
How to input / output IBM mainframe files in Java?
[Java] How to play rock-paper-scissors (equivalent to paiza rank A)
[Java] How to extract the file name from the path
[For beginners] How to operate Stream API after Java 8
[Android Studio] [Java] How to fix the screen vertically
Summary of Java communication API (1) How to use Socket
Summary of Java communication API (3) How to use SocketChannel
How to convert A to a and a to A using AND and OR in Java
How to use Play Framework without using typesafe activator
Summary of Java communication API (2) How to use HttpUrlConnection
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
[Java] How to use Map
How to use Maven to place resource files outside the JAR
How to use Chain API
How to lower java version
[Java] How to use Map
How to uninstall Java 8 (Mac)
Java to play with Function
Java --How to make JTable
[Must-see for apprentice java engineer] How to use Stream API
Difference between Java and JavaScript (how to find the average)
How to use java Optional
How to minimize Java images
How to write java comments