Java声音API
JavaSound是Java用于影响和控制声音媒体的类和接口的集合。它由两个包组成。
- javax.sound.sampled:这个包提供了一个用于捕获、混合数字音频的接口。
- javax.sound.midi:这个包为MIDI(乐器数字接口)合成、排序和事件传输提供了一个接口。
什么是MIDI?
我们将在这里探索更多关于 MIDI 的 MIDI。所以 MIDI 就像一张音符表,支持 MIDI 的乐器可以播放,将其视为 HTML 文档,将支持 MIDI 的乐器视为 Web 浏览器。 MIDI 文件包含有关如何播放歌曲的信息,就像吉他手的说明书一样。 MIDI 设备知道如何读取 MIDI 文件并生成声音。
为了发出真实的声音,我们需要四件事:
- 乐器(播放音乐) SEQUENCER
- Song(要播放的音乐) SEQUENCE
- 轨道(保存音符)
- 音符(实际音乐信息)MIDI EVENTS
JavaSound API 涵盖了所有这些。
SEQUENCER ⇒ SEQUENCE ⇒ TRACK ⇒ MIDI EVENTS
程序:
第 1 步:获取一个Sequencer并打开它
// Make a sequencer named player and open it
Sequencer player = MIDISystem.getSequencer();
player.open();
第 2 步:创建一个新序列
// Make a new sequence
Sequence seq = new Sequence(Sequence.PPQ, 4);
第 3 步:从序列中获取新曲目
// Creating new Track
Track t = seq.createTrack();
第 4 步:用MIDIEVENTS填充音轨
// Filling the Track with MidiEvent and
// giving the Secquence to the Sequencer
t.add(myMidiEvent1);
player.setSequence(seq);
// Play it using start
player.start();
执行:
例子
Java
// Java Program to Illustrate JAva Sounf API
// Importing classes frpm
// javax.sound package
import javax.sound.midi.*;
// Main class
// MiniMusicApp
public class GFG {
// Method 1
// Main driver method
public static void main(String[] args)
{
// Creating object of class inside main()
GFG minimusic = new GFG();
// Calling method 2 to play the sound
minimusic.play();
// Display message on the console for
// succesful execution of program
System.out.print(
"Successfully compiled and executed");
}
// Method 2
// To play the sound
public void play()
{
// Try block to check for exceptions
try {
// Getting a sequencer and open it
Sequencer player = MidiSystem.getSequencer();
player.open();
// Making 1a new Sequence
Sequence seq = new Sequence(Sequence.PPQ, 4);
// Creating a new track
Track track = seq.createTrack();
// Making a Message
ShortMessage a = new ShortMessage();
// Put the Instruction in the Message
a.setMessage(144, 1, 44, 100);
// Make a new MidiEvent
MidiEvent noteOn = new MidiEvent(a, 1);
// Add MidiEvent to the Track
track.add(noteOn);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
// Giving secquence to Sequencer
player.setSequence(seq);
// Start the Sequencer using start() method
player.start();
}
// Catch block to handle exceptions
catch (Exception ex) {
// Diusplay the exception on console
// along with line number
ex.printStackTrace();
}
}
}
输出:
Successfully compiled and executed