JAVAIt does not have much advantage in multimedia processing, but we sometimes need some music in the program.
WavIf there are large waveform audio files, it is better to use MIDI for background music. However, many online MIDI playback tutorials are simple examples.
The resource release issue is not considered. If the program runs for a long time, the more memory consumption occurs, and
Java. lang. OutOfMemoryError ..
In MIDI playback, a class is important, that is
MidiSystemClass, responsible for the management of the entire MIDI playing device, is actually
SeqencerIt is a MIDI playback setting used to play the MIDI sequence. Another class is called
SeqenceIt is the MIDI sequence, which can be generated by the program or read from the file or URL.
Copy codeThe Code is as follows: package test1;
Import java. io. File;
Import java. io. IOException;
Import java. io. InputStream;
Import java. util. Hashtable;
Import java. util. Map;
Import java. util. logging. Level;
Import java. util. logging. Logger;
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 Test5 implements Runnable {
Private Sequencer midi;
Private String [] names = {"1.mid"," 2.mid", "3.mid"," 4.mid", "5.mid "};
Private int I;
Private Map <String, Sequence> map;
Public Test5 (){
InitMap ();
New Thread (this). start ();
}
Private void initMap (){
Try {
Map = new Hashtable <String, Sequence> ();
Midi = MidiSystem. getSequencer (false );
Midi. open ();
For (String s: names ){
Try {
Sequence s1 = MidiSystem. getSequence (new File (s ));
Map. put (s, s1 );
} Catch (InvalidMidiDataException ex ){
Logger. getLogger (Test5.class. getName (). log (Level. SEVERE, null, ex );
} Catch (IOException ex ){
Logger. getLogger (Test5.class. getName (). log (Level. SEVERE, null, ex );
}
}
} Catch (MidiUnavailableException ex ){
Logger. getLogger (Test5.class. getName (). log (Level. SEVERE, null, ex );
}
}
Private void createPlayer (String name ){
Try {
Sequence se = map. get (name );
Midi. setSequence (se );
Midi. start ();
} Catch (InvalidMidiDataException ex ){
Logger. getLogger (Test5.class. getName (). log (Level. SEVERE, null, ex );
}
}
Public void run (){
While (true ){
Try {
System. out. println ("changed file." + (++ I ));
String name = names [(int) (Math. random () * names. length)];
CreatePlayer (name );
Thread. sleep (10000 );
} Catch (InterruptedException ex ){
Logger. getLogger (Test5.class. getName (). log (Level. SEVERE, null, ex );
}
}
}
Public static void main (String [] args ){
New Test5 ();
}
}
It is very important to note that when a program is runningSeqencerI used to generateSeqencerBecause at that time I thought I would call itClose ()Method, can it be opened? In fact, it can be opened again, that is, the idea that the program will eventually crash due to memory overflow.