How can I play the MIDI file directly from memory (e.g. Resources)? I found this as a solution, but I do not understand how to play the MIDI from resources. Help me with the right WinAPI command please
Asked
Active
Viewed 2,148 times
3
-
1You have to explicitly load the file from the project Resources into memory. It's not clear what part of the linked code isn't working for you. – Cody Gray - on strike May 21 '11 at 16:49
-
private static void _Open(string sFileName) is working for some file on the disk, it is pretty simple. My question is how to call the WinAPI function from the MemoryStream – Killster May 21 '11 at 17:10
3 Answers
1
Ok, i made kind of a temporary solution. Still, it works
using (var midiStream = new MemoryStream(Resources.myMidi))
{
var data = midiStream.ToArray();
try
{
using (var fs = new FileStream("midi.mid", FileMode.CreateNew, FileAccess.Write))
{
fs.Write(data, 0, data.Length);
}
}
catch(IOException)
{}
string sCommand = "open \"" + Application.StartupPath + "/midi.mid" + "\" alias " + "MIDIapp";
mciSendString(sCommand, null, 0, IntPtr.Zero);
sCommand = "play " + "MIDIapp";
mciSendString(sCommand, null, 0, IntPtr.Zero);
}

Killster
- 69
- 5
0
You can use a .NET library that has playback functionality. DryWetMIDI allows this (example shows playing a MIDI file via default Windows synthesizer):
var midiFile = MidiFile.Read("Greatest song ever.mid");
// Or you can read a MIDI file from a stream
// var midiFile = MidiFile.Read(stream);
using (var outputDevice = OutputDevice.GetByName("Microsoft GS Wavetable Synth"))
{
midiFile.Play(outputDevice);
}
You can read more about playing MIDI data on the library docs: Playback.

Maxim
- 1,995
- 1
- 19
- 24
0
You can use the SoundPlayer class:
using (Stream midi = Resources.ResourceManager.GetStream("myMidi"))
{
using (SoundPlayer player = new SoundPlayer(midi))
{
player.Play();
}
}

Simon Mourier
- 132,049
- 21
- 248
- 298
-
I got an 'Invalid operation exception' (The value of the specified resource is not a MemoryStream object.) I tried this code: `using (Stream midi = new MemoryStream(Resources.myMidi)) { using (SoundPlayer player = new SoundPlayer(midi)) { player.Play(); } }` , but there is an invalid operation exception in the Play() method.. Maybe my MIDI is wrong? – Killster May 21 '11 at 17:24
-
5
-