B4J Library [B4j] Javax Midi Lib

Here is a wrap of the JavaxMidi Library as a B4xLib.

It is a large library and I haven't tested all of the available methods, it you get any problems let me know and I'll take a look.

The code is in the b4xlib, but only supports B4j feel free to unzip it and use it as you wish.

The example attached is a simple midi player and dump viewer for the midi tracks and has no additional dependencies.

1580318838133.png




Depends on: JavaObject and ByteConverter.

Documentation for the library is in the attached XMLfile which you can open with one of the Document viewers available on the Forum. Documentation and examples for the JavaxMidi package are available on the internet,

As always, if you try it, let me know how you get on with it and please report any bugs or problems.

Update to V1.2
Amended to work with external midi devices. (see post #7)

Update to V1.3
Fixed bug in soundfont initialization (Thanks luca1967 for finding it)

Update to V 1.4
  • Added TransposeTrack2 to MidiUtils which allows ignoring transpose on certain midi channels.
  • Fixed bug in MidiSynthesizer GetLoadedInstruments
Update to V 1.5 - Breaking Change
  • Added ChrSet where needed to allow use of different character encoding for text events in a midifile.
  • Added VirtualMachinArgs and PackagerProperty to the example project as required to create a package on Java9+ (Uncomment the 2 lines)
It will be obvious in the IDE where the changes are required, I suggest you used "UTF-8" for the characterset unless you know it needs something different.

Update to V 1.6 - Breaking Change (if using a transmitter listener)
  • Amended MidiData_Event in MidiTransmitter class to return a MidiMessage instead of MidiShortMessage See this post for modifications required
Update to V 1.7
  • Modified MidiySytemStatic GetSequence2 and GetSequence3 to return wrapped Sequence Objects
Update to V 1.8
  • Fixed bug in MidiSystemGetMidiFileFormat3
  • Bug Fixes
Update to V 1.9
Modified for compatibility with B4j V10.20 Beta +
 

Attachments

  • JavaxMidi.xml
    124.8 KB · Views: 661
  • JavaxMidi-b4xlib.b4xlib
    42.2 KB · Views: 34
  • jMidiLib1-9.zip
    78.1 KB · Views: 26
Last edited:

mahmood6126

New Member
hi stevel05.
In the beginning, I thank you for this great library and apologies for my bad english because that's not my native langues.
i have a question about using this library and i hope you help me to solve my problem. i want to creat an app about send and receive MIDI messages from my electronic piano(Yamaha DGX-670). but i dont know how can i do this with this library.
please show me how can i do it.

*. i write this project with JavaScript last year ago and i just want to write this with b4j.
 

stevel05

Expert
Licensed User
Longtime User
please show me how can i do it.
I'm sorry but the question is far too vague. It would take many hours to write a complete answer.

Most of the information you will need are in the demo apps already provided, playing midi is in the original demo, receiving from a keyboard can be found here.

Break it down into small questions and I will help where I can.

Javax midi implementation is a little cumbersome, you can find information about it here.
 

LucaMs

Expert
Licensed User
Longtime User
Since the author is online, @stevel05, I'll take the liberty of writing this little thing here instead of in "Chit Chat" (the topic is inherent, obviously, and also concerns ChatGPT).

I had a song in mind and while humming it, I thought: "How beautiful it would be without the singer's voice but only saxophone".
Unfortunately I then forgot what the song was, but I asked ChatGPT to generate a score of a few bars, for saxophone.

Try to do the same thing 😁 :confused:

https://chatgpt.com/share/67b54d95-2400-8002-8319-e32d5ed6e0a3
 

stevel05

Expert
Licensed User
Longtime User
Try to do the same thing. I did play with getting chat GPT to generate midi data about a year ago. The results were not great, but I haven't tried it since. May have to give it another go.
 

LucaMs

Expert
Licensed User
Longtime User
ChatGPT (chatgpt.com):
If you want me to generate a MIDI, I can do that and provide you with the file. You tell me! 🎷😊

Me:
You could not generate the .mscz file, so I don't think you can generate the midi file (more likely you won't be able to attach it), but try.

ChatGPT:
I can't generate the MIDI file directly here, because the necessary module is not available.
However, you can easily create the MIDI file in MuseScore by following these steps:
<omissis>
If you want, I can provide you with the Python code that you could run on your PC to generate the MIDI file. Let me know! 😊

Me:
You say the necessary module is not available here; where would it be?

ChatGPT:
The MIDIUtil module (or alternatives like mido and music21 ) is available in a normal Python environment on a PC with Python installed. You can install it and run the code on your computer.

📌 Here's how:
Install the module
Open the terminal (or command prompt) and type:
B4X:
pip install midiutil

Create a Python script
Open a text editor (e.g. Notepad++, VS Code or PyCharm).
Copy and paste the code I will provide.
Save the file as generate_midi.py .

Run the script
Open the terminal and type:
B4X:
python generate_midi.py

You will get a Saxophone_Melody.mid file that you can open with MuseScore or other MIDI software.

Do you want me to directly provide you with the Python code to copy? 😊

Me: Yes

ChatGPT:
Ecco il codice Python che puoi eseguire sul tuo PC per generare il file MIDI:
B4X:
from midiutil import MIDIFile

# Creiamo un file MIDI
midi = MIDIFile(1)  # Una traccia
midi.addTempo(0, 0, 90)  # Imposta BPM a 90

# Note per il sassofono (canale 0, durata in quarti)
melody = [
    (60, 1), (64, 1), (67, 1), (69, 1),  # C4, E4, G4, A4
    (67, 1), (65, 1), (64, 1), (62, 1),  # G4, F4, E4, D4
    (60, 1), (62, 1), (64, 1), (65, 1),  # C4, D4, E4, F4
    (64, 1), (62, 1), (60, 1), (0, 2),   # E4, D4, C4, pausa minima
    (67, 1), (69, 0.5), (72, 0.5), (74, 1),  # G4, A4, C5, D5
    (72, 1), (71, 1), (69, 1), (67, 1),  # C5, B4, A4, G4
    (64, 1), (65, 0.5), (67, 0.5), (69, 1),  # E4, F4, G4, A4
    (67, 1), (64, 1), (60, 2)            # G4, E4, C4 (minima)
]

# Aggiunta delle note
time = 0
for pitch, duration in melody:
    if pitch > 0:
        midi.addNote(0, 0, pitch, time, duration, 100)  # Volume 100
    time += duration

# Salviamo il file MIDI
with open("Saxophone_Melody.mid", "wb") as output_file:
    midi.writeFile(output_file)

print("File MIDI generato: Saxophone_Melody.mid")

📌 How to use it
Install Python if you don't have it already (download it from python.org ).
Install the necessary library with:
B4X:
pip install midiutil
Copy and paste the code into a file called generate_midi.py .
Open the terminal in the folder where you saved the file and type:
B4X:
python generate_midi.py

You will find the file Saxophone_Melody.mid in the same folder.
Now you can open it in MuseScore or a MIDI sequencer! 🎷😊



I'll have to study for an hour! I think I saw a tip on how to use VSCode here on b4x.com. And at least another hour for PyBridge.
 

stevel05

Expert
Licensed User
Longtime User
And with PyBridge

Create a new Project using PyBridge with Python.

edit: Beta 2 + Create a new Project using PyBridge, you will also need to create a local Python Runtime. Click the IDE Link before the next step. Or change the code to point to an already installed version

Replace B4xMainPage code with this:

B4X:
'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip
#CustomBuildAction: after packager, %WINDIR%\System32\robocopy.exe, Python temp\build\bin\python /E /XD __pycache__ Doc pip setuptools tests

'Ctrl + click to open Python shell: ide://run?File=%PROJECT%\Objects\Python\WinPython+Command+Prompt.exe
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Public Py As PyBridge
End Sub

Public Sub Initialize
 
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
    Py.Initialize(Me, "Py")
    Dim opt As PyOptions = Py.CreateOptions(File.Combine(File.DirApp, "Python/python/python.exe"))
    Py.Start(opt)
    Wait For Py_Connected (Success As Boolean)
    If Success = False Then
        LogError("Failed to start Python process.")
        Return
    End If
    PrintPythonVersion
    ExampleOfPythonMethod
 
End Sub

Private Sub B4XPage_Background
    Py.KillProcess
End Sub

Private Sub Py_Disconnected
    Log("PyBridge disconnected")
End Sub

Private Sub PrintPythonVersion
    Dim version As PyWrapper = Py.ImportModuleFrom("sys", "version")
    version.Print2("Python version:", "", False)
End Sub

'Tip: start typing Py and use the Py macros to create such methods:
Private Sub ExampleOfPythonMethod
    Dim Code As String = $"
from midiutil import MIDIFile

# Creiamo un file MIDI
midi = MIDIFile(1)  # Una traccia
midi.addTempo(0, 0, 90)  # Imposta BPM a 90

# Note per il sassofono (canale 0, durata in quarti)
melody = [
    (60, 1), (64, 1), (67, 1), (69, 1),  # C4, E4, G4, A4
    (67, 1), (65, 1), (64, 1), (62, 1),  # G4, F4, E4, D4
    (60, 1), (62, 1), (64, 1), (65, 1),  # C4, D4, E4, F4
    (64, 1), (62, 1), (60, 1), (0, 2),   # E4, D4, C4, pausa minima
    (67, 1), (69, 0.5), (72, 0.5), (74, 1),  # G4, A4, C5, D5
    (72, 1), (71, 1), (69, 1), (67, 1),  # C5, B4, A4, G4
    (64, 1), (65, 0.5), (67, 0.5), (69, 1),  # E4, F4, G4, A4
    (67, 1), (64, 1), (60, 2)            # G4, E4, C4 (minima)
]

# Aggiunta delle note
time = 0
for pitch, duration in melody:
    if pitch > 0:
        midi.addNote(0, 0, pitch, time, duration, 100)  # Volume 100
    time += duration

# Salviamo il file MIDI
with open("Saxophone_Melody.mid", "wb") as output_file:
    midi.writeFile(output_file)

print("File MIDI generato: Saxophone_Melody.mid")
"$
    Py.RunNoArgsCode(Code)
 
End Sub


Click the link at the top of the B4xMainPage Module to open the Python Shell and type: "pip install midiutils" once complete Run the project.

Midi file will be created in the projects Objects Folder.
 
Last edited:
Top