本文整理汇总了C++中MidiMessage::getTimeStamp方法的典型用法代码示例。如果您正苦于以下问题:C++ MidiMessage::getTimeStamp方法的具体用法?C++ MidiMessage::getTimeStamp怎么用?C++ MidiMessage::getTimeStamp使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MidiMessage
的用法示例。
在下文中一共展示了MidiMessage::getTimeStamp方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: handleEvent
void WiFiOutput::handleEvent(int eventType, MidiMessage& event, int sampleNum)
{
if (eventType == TTL)
{
startTimer((int) float(event.getTimeStamp())/getSampleRate()*1000.0);
}
}
示例2: handleIncomingMidiMessage
//==============================================================================
void MiosTerminal::handleIncomingMidiMessage(const MidiMessage& message, uint8 runningStatus)
{
uint8 *data = (uint8 *)message.getRawData();
uint32 size = message.getRawDataSize();
int messageOffset = 0;
bool messageReceived = false;
if( runningStatus == 0xf0 &&
SysexHelper::isValidMios32DebugMessage(data, size, -1) &&
(data[7] == 0x40 || data[7] == 0x00) ) { // allow 0x40 (received) and 0x00 (sent) terminal message
// 0x00 is allowed for the "feedback test" which is described in the MIDI troubleshooting guide
messageOffset = 8;
messageReceived = true;
}
if( messageReceived ) {
String str = "";
for(int i=messageOffset; i<size; ++i) {
if( data[i] < 0x80 ) {
if( data[i] != '\n' || size < (i+1) )
str += String::formatted(T("%c"), data[i] & 0x7f);
}
}
if( !gotFirstMessage )
terminalLogBox->clear();
gotFirstMessage = 1;
double timeStamp = message.getTimeStamp() ? message.getTimeStamp() : ((double)Time::getMillisecondCounter() / 1000.0);
String timeStampStr = (timeStamp > 0)
? String::formatted(T("%8.3f"), timeStamp)
: T("now");
String terminalStr = "[" + timeStampStr + "] " + str;
if( miosStudio->runningInBatchMode() ) {
std::cout << terminalStr << std::endl;
} else {
terminalLogBox->addEntry(Colours::black, terminalStr);
}
}
}
示例3: addMessageToQueue
void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
{
#if JUCE_DEBUG
jassert (hasCalledReset); // you need to call reset() to set the correct sample rate before using this object
#endif
// the messages that come in here need to be time-stamped correctly - see MidiInput
// for details of what the number should be.
jassert (message.getTimeStamp() != 0);
const ScopedLock sl (midiCallbackLock);
auto sampleNumber = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
incomingMessages.addEvent (message, sampleNumber);
// if the messages don't get used for over a second, we'd better
// get rid of any old ones to avoid the queue getting too big
if (sampleNumber > sampleRate)
incomingMessages.clear (0, sampleNumber - (int) sampleRate);
}
示例4: getControllerIndexed
//==============================================================================
void MidiSequencePlugin::getControllerIndexed (const int index, int& controllerNum, double& value, double& beat)
{
int numNoteOn = 0;
for (int i = 0; i < midiSequence->getNumEvents (); i++)
{
MidiMessageSequence::MidiEventHolder* eventOn = midiSequence->getEventPointer (i);
MidiMessage* msgOn = & eventOn->message;
if (eventOn->message.isController ())
{
if (index == numNoteOn)
{
controllerNum = msgOn->getControllerNumber();
value = msgOn->getControllerValue () / 127.0;
beat = msgOn->getTimeStamp ();
break;
}
numNoteOn++;
}
}
}
示例5: processBlock
void CtrlrPanelProcessor::processBlock(MidiBuffer &midiMessages, MidiBuffer &leftoverBuffer)
{
if (owner.getMidiOptionBool(panelMidiInputFromHostCompare))
{
owner.getMIDIInputThread().handleMIDIFromHost(midiMessages);
}
MidiBuffer::Iterator i(midiMessages);
MidiMessage m;
int time;
while (i.getNextEvent(m,time))
{
_MIN("VST INPUT", m);
if (owner.getMidiOptionBool(panelMidiThruH2D) == true)
{
if (owner.getMidiOptionBool(panelMidiThruH2DChannelize))
{
m.setChannel (owner.getMidiChannel(panelMidiOutputChannelDevice));
}
owner.sendMidi(m);
}
if (owner.getMidiOptionBool(panelMidiThruH2H) == true)
{
if (owner.getMidiOptionBool(panelMidiThruH2HChannelize))
{
m.setChannel (owner.getMidiChannel(panelMidiOutputChannelHost));
}
leftoverBuffer.addEvent (m, m.getTimeStamp());
}
}
}
示例6: processBlock
//==============================================================================
void MidiSequencePlugin::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
{
MidiSequencePluginBase::processBlock(buffer, midiMessages);
MidiMessageSequence sourceMidi = *midiSequence;
std::vector<int> doneTheseControllers;
if (transport->isPlaying () && getBoolValue(PROP_SEQENABLED, true))
{
const int blockSize = buffer.getNumSamples ();
MidiBuffer* midiBuffer = midiBuffers.getUnchecked (0);
const int frameCounter = transport->getPositionInFrames ();
const int framesPerBeat = transport->getFramesPerBeat ();
const int nextBlockFrameNumber = frameCounter + blockSize;
const int seqIndex = getLoopRepeatIndex();
const double beatCount = getLoopBeatPosition();
const double frameLenBeatCount = (nextBlockFrameNumber - frameCounter) / (double)framesPerBeat;
double frameEndBeatCount = beatCount + frameLenBeatCount;
if (frameEndBeatCount > getLengthInBeats())
frameEndBeatCount -= getLengthInBeats();
// loop for each controller we need to interpolate
MidiMessage* lastCtrlEvent = NULL;
do
{
lastCtrlEvent = NULL;
// hunt for a controller event before now
int i;
for (i = 0; i < sourceMidi.getNumEvents (); i++)
{
int timeStampInSeq = roundFloatToInt (sourceMidi.getEventTime (i) * framesPerBeat);
int timeStamp = timeStampInSeq + (seqIndex * getLengthInBeats() * framesPerBeat);
MidiMessage* midiMessage = &sourceMidi.getEventPointer (i)->message;
if (timeStamp >= nextBlockFrameNumber || !midiMessage)
break; // event is after now, leave
//if (midiMessage->isController() && (std::find(doneTheseControllers.begin(), doneTheseControllers.end(), midiMessage->getControllerNumber()) == doneTheseControllers.end()))
// lastCtrlEvent = midiMessage;
}
// hunt for a matching event after that one
if (lastCtrlEvent)
{
// store the controller number so we know which controllers we've done
doneTheseControllers.push_back(lastCtrlEvent->getControllerNumber());
MidiMessage* nextCtrlEvent = NULL;
for (; i < sourceMidi.getNumEvents (); i++)
{
MidiMessage* midiMessage = &sourceMidi.getEventPointer (i)->message;
if (midiMessage->isController() && midiMessage->getControllerNumber() == lastCtrlEvent->getControllerNumber())
{
nextCtrlEvent = midiMessage;
break;
}
}
// render an interpolated event!...
if (nextCtrlEvent)
{
double bt = nextCtrlEvent->getTimeStamp();
double at = lastCtrlEvent->getTimeStamp();
double deltaBeats = bt - at;
int a = lastCtrlEvent->getControllerValue();
int b = nextCtrlEvent->getControllerValue();
double now = beatCount + (frameEndBeatCount - beatCount) / 2.0;
double interpRemainBeats = deltaBeats - (now - at);
if (deltaBeats > 0)
{
double nextPart = interpRemainBeats / deltaBeats;
nextPart = 1 - nextPart;
double interpdVal = a + nextPart * (b - a);
MidiMessage interpy = MidiMessage::controllerEvent(lastCtrlEvent->getChannel(), lastCtrlEvent->getControllerNumber(), static_cast<int>(interpdVal));
midiBuffer->addEvent (interpy, (nextBlockFrameNumber - frameCounter) / 2);
}
else
{
DBG ("Negative delta beats when rendering automation!!");
}
}
}
// now we also need to do that again if there are multiple events per frame AND we are interpolating multiple times per frame
// (at the moment only interpolating once per audio frame)
} while (lastCtrlEvent != NULL);
}
}
示例7: menuItemSelected
virtual void menuItemSelected(int menuItemID, int)
{
if (menuItemID == 200)
{
WildcardFileFilter wildcardFilter("*.mid", String::empty, "Midi files");
FileBrowserComponent browser(FileBrowserComponent::canSelectFiles | FileBrowserComponent::openMode,
lastOpenedFile.exists() ? lastOpenedFile : File(String("C:\\Users\\GeorgeKrueger\\Documents")), &wildcardFilter, nullptr);
FileChooserDialogBox dialogBox("Open a midi file",
"Please choose a midi file to open...",
browser,
false,
Colours::lightgrey);
if (dialogBox.show())
{
File selectedFile = browser.getSelectedFile(0);
lastOpenedFile = selectedFile;
FileInputStream fileStream(selectedFile);
juce::MidiFile midiFile;
midiFile.readFrom(fileStream);
int numTracks = midiFile.getNumTracks();
midiFile.convertTimestampTicksToSeconds();
String msg;
msg << "Opened midi file: " << selectedFile.getFileName() << " Tracks: " << numTracks << "\n";
log(msg);
for (int i = 0; i < numTracks; ++i)
{
const MidiMessageSequence* msgSeq = midiFile.getTrack(i);
OwnedArray<PluginDescription> results;
String plugFile = "C:\\VST\\FMMF.dll";
VSTPluginFormat vstFormat;
vstFormat.findAllTypesForFile(results, plugFile);
if (results.size() > 0) {
msg.clear();
msg << "Found " << results.size() << " plugin(s) matching file " << plugFile << "\n";
log(msg);
int secsToRender = 10;
double sampleRate = 44100;
int totalSizeInSamples = static_cast<int>(44100 * secsToRender);
AudioPluginInstance* plugInst = vstFormat.createInstanceFromDescription(*results[0], sampleRate, totalSizeInSamples);
if (!plugInst) {
msg.clear();
msg << "Failed to load plugin " << plugFile << "\n";
log(msg);
continue;
}
int numInputChannels = plugInst->getTotalNumInputChannels();
int numOutputChannels = plugInst->getTotalNumOutputChannels();
msg.clear();
msg << "Plugin input channels: " << numInputChannels << " output channels: " << numOutputChannels
<< " Current program: " << plugInst->getCurrentProgram() << "\n";
log(msg);
int maxChannels = std::max(numInputChannels, numOutputChannels);
AudioBuffer<float> buffer(maxChannels, totalSizeInSamples);
MidiBuffer midiMessages;
for (int j = 0; j < msgSeq->getNumEvents(); ++j)
{
MidiMessageSequence::MidiEventHolder* midiEventHolder = msgSeq->getEventPointer(j);
MidiMessage midiMsg = midiEventHolder->message;
int samplePos = static_cast<int>(midiMsg.getTimeStamp() * sampleRate);
midiMessages.addEvent(midiMsg, samplePos);
}
plugInst->prepareToPlay(sampleRate, totalSizeInSamples);
plugInst->processBlock(buffer, midiMessages);
/*File txtOutFile("C:\\Users\\GeorgeKrueger\\Documents\\GitHub\\soundserver2\\out.txt");
FileOutputStream* txtOutStream = txtOutFile.createOutputStream();
for (int j = 0; j < 44100; ++j)
{
float sample = buffer.getSample(0, j);
txtOutStream->writeFloat(sample);
txtOutStream->writeText(" ", true, false);
}*/
File outputFile("C:\\Users\\GeorgeKrueger\\Documents\\GitHub\\soundserver2\\out.wav");
if (outputFile.exists()) {
outputFile.deleteFile();
}
FileOutputStream* fileOutputStream = outputFile.createOutputStream();
WavAudioFormat wavFormat;
StringPairArray metadataValues;
juce::AudioFormatWriter* wavFormatWriter = wavFormat.createWriterFor(
fileOutputStream, sampleRate, 2, 16, metadataValues, 0);
bool writeAudioDataRet = wavFormatWriter->writeFromAudioSampleBuffer(buffer, 0, buffer.getNumSamples());
wavFormatWriter->flush();
msg.clear();
msg << "Done writing to output file " << outputFile.getFileName() << " . Write return value: "
<< (int)writeAudioDataRet << "\n";
log(msg);
delete wavFormatWriter;
delete plugInst;
//.........这里部分代码省略.........
示例8: handleEvent
void LfpDisplayNode::handleEvent(int eventType, MidiMessage& event, int sampleNum)
{
if (eventType == TTL)
{
const uint8* dataptr = event.getRawData();
//int eventNodeId = *(dataptr+1);
int eventId = *(dataptr+2);
int eventChannel = *(dataptr+3);
int eventTime = event.getTimeStamp();
int eventSourceNodeId = *(dataptr+5);
int nSamples = numSamples.at(eventSourceNodeId);
int samplesToFill = nSamples - eventTime;
// std::cout << "Received event from " << eventSourceNode << ", channel "
// << eventChannel << ", with ID " << eventId << ", copying to "
// << channelForEventSource[eventSourceNode] << std::endl;
////
int bufferIndex = (displayBufferIndex[channelForEventSource[eventSourceNodeId]] + eventTime - nSamples) % displayBuffer->getNumSamples();
if (eventId == 1)
{
ttlState[eventSourceNodeId] |= (1L << eventChannel);
}
else
{
ttlState[eventSourceNodeId] &= ~(1L << eventChannel);
}
if (samplesToFill + bufferIndex < displayBuffer->getNumSamples())
{
//std::cout << bufferIndex << " " << samplesToFill << " " << ttlState[eventSourceNode] << std::endl;
displayBuffer->copyFrom(channelForEventSource[eventSourceNodeId], // destChannel
bufferIndex, // destStartSample
arrayOfOnes, // source
samplesToFill, // numSamples
float(ttlState[eventSourceNodeId])); // gain
}
else
{
int block2Size = (samplesToFill + bufferIndex) % displayBuffer->getNumSamples();
int block1Size = samplesToFill - block2Size;
//std::cout << "OVERFLOW." << std::endl;
//std::cout << bufferIndex << " " << block1Size << " " << ttlState << std::endl;
displayBuffer->copyFrom(channelForEventSource[eventSourceNodeId], // destChannel
bufferIndex, // destStartSample
arrayOfOnes, // source
block1Size, // numSamples
float(ttlState[eventSourceNodeId])); // gain
//std::cout << 0 << " " << block2Size << " " << ttlState << std::endl;
displayBuffer->copyFrom(channelForEventSource[eventSourceNodeId], // destChannel
0, // destStartSample
arrayOfOnes, // source
block2Size, // numSamples
float(ttlState[eventSourceNodeId])); // gain
}
// std::cout << "ttlState: " << ttlState << std::endl;
// std::cout << "Received event from " << eventNodeId <<
// " on channel " << eventChannel <<
// " with value " << eventId <<
// " at timestamp " << event.getTimeStamp() << std::endl;
}
}
示例9: main
//.........这里部分代码省略.........
do {
std::map<std::string, double> key_position;
time_scale_changed = false;
gcode.clear();
heeks.clear();
key_position.clear();
std::ostringstream l_ossGCode;
for (int track = 0; track<midi_file.getNumTracks(); track++)
{
int number_of_notes_included = 0;
int number_of_notes_ignored = 0;
const MidiMessageSequence *pMessageSequence = midi_file.getTrack(track);
double start_time = pMessageSequence->getStartTime();
double end_time = pMessageSequence->getEndTime();
double duration = end_time - start_time;
if (duration <= 0.0001) continue;
l_ossGCode.str("");
l_ossGCode << "(Duration of track " << track << " is " << duration << " seconds)";
gcode.push_back( l_ossGCode.str() );
printf("%s\n", l_ossGCode.str().c_str());
// printf("Duration of track %d is %lf seconds\n", track, duration);
for (int event = 0; event < pMessageSequence->getNumEvents(); event++)
{
MidiMessageSequence::MidiEventHolder *pEvent = pMessageSequence->getEventPointer(event);
MidiMessage message = pEvent->message;
double time_stamp = message.getTimeStamp();
if (message.isTextMetaEvent())
{
String text = message.getTextFromTextMetaEvent();
char buf[1024];
memset( buf, '\0', sizeof(buf) );
text.copyToBuffer( buf, sizeof(buf)-1 );
// printf("Track %d is %s\n", track, buf );
l_ossGCode.str("");
l_ossGCode << "(Text track " << track << " is " << buf << ")";
gcode.push_back(l_ossGCode.str());
printf("%s\n", l_ossGCode.str().c_str());
std::ostringstream l_ossHeeks;
l_ossHeeks << "<Text text=\"" << buf << "\" font=\"OpenGL\" col=\"0\" m0=\"-0.0443342566\" m1=\"-0.999016753\" m2=\"0\" m3=\"" << (double) (time_stamp * mm_per_second) << "\" m4=\"0.999016753\" m5=\"-0.0443342566\" m6=\"0\" m7=\"" << (double) ((track_width + space_between_tracks) * track) << "\" m8=\"0\" m9=\"0\" ma=\"1\" mb=\"0\" id=\"" << id++ << "\" />";
heeks.push_back( l_ossHeeks.str() );
}
if (message.isTrackNameEvent())
{
String text = message.getTextFromTextMetaEvent();
char buf[1024];
memset( buf, '\0', sizeof(buf) );
text.copyToBuffer( buf, sizeof(buf)-1 );
printf("Track %d is %s\n", track, buf );
}
if (message.isNoteOn())
{
char note_name[256];
memset( note_name, '\0', sizeof(note_name) );
message.getMidiNoteName(message.getNoteNumber(), true, true, middle_c_octave).copyToBuffer( note_name, sizeof(note_name)-1 );
示例10: run
void MidiThread::run() {
midiPort = MidiOutput::openDevice(0);
map<double, double>::iterator tempoIterator = tempos.begin();
double tickLength = tempoIterator->second;
double initTempo = 60000 / (tickLength * ppq);
tempoIterator++;
map<double, std::pair<int, int>>::iterator timeSigIterator = timeSigs.begin();
int timeSigNumerator = timeSigIterator->second.first;
int timeSigDenominator = timeSigIterator->second.second;
timeSigIterator++;
MidiMessage message;
// MIDI click intro
File clickFile("Click120.mid");
ScopedPointer<FileInputStream> clickStream = clickFile.createInputStream();
double eventTick;
double prevTick = 0;
double prevDelta = 0;
int now = Time::getMillisecondCounter();
if (clickStream) {
click.readFrom(*clickStream);
short clickPpq = click.getTimeFormat();
MidiMessageSequence clickSequence = MidiMessageSequence();
clickSequence = *click.getTrack(0);
int i = 0;
while (i < clickSequence.getNumEvents()) {
message = clickSequence.getEventPointer(i)->message;
eventTick = message.getTimeStamp();
double origBpm = 60000 / (tickLength * clickPpq);
double delta = prevDelta + ((eventTick - prevTick) * (origBpm / initTempo)) * tickLength;
Time::waitForMillisecondCounter(now + delta);
midiPort->sendMessageNow(message);
i++;
prevTick = eventTick;
prevDelta = delta;
}
}
now = Time::getMillisecondCounter();
prevTick = 0;
prevDelta = 0;
int currentBar = 1;
int currentBeat = 1;
int currentTick = 0;
int quartersPerBar = timeSigNumerator * (timeSigDenominator / 4);
int tickStartOfBar = 0;
int tickStartNextBar = quartersPerBar * ppq;
currentBpm = initTempo;
int i = 0;
while (i < midiSequence.getNumEvents() && !threadShouldExit()) {
std::stringstream ss;
ss << currentBpm;
content->updateBpm(ss.str());
message = midiSequence.getEventPointer(i)->message;
eventTick = message.getTimeStamp(); // number of midi ticks until note
if (tempoIterator != tempos.end() && eventTick >= tempoIterator->first) {
tickLength = tempoIterator->second;
tempoIterator++;
}
if (timeSigIterator != timeSigs.end() && eventTick >= timeSigIterator->first) {
timeSigNumerator = timeSigIterator->second.first;
timeSigDenominator = timeSigIterator->second.second;
quartersPerBar = timeSigNumerator * (4 / timeSigDenominator);
timeSigIterator++;
}
if (eventTick >= tickStartNextBar) {
tickStartOfBar = tickStartNextBar;
tickStartNextBar = tickStartOfBar + quartersPerBar * ppq;
currentBar = currentBar + static_cast<int> (std::floor((eventTick - tickStartOfBar) / (ppq * quartersPerBar))) + 1;
}
currentBeat = static_cast<int> (std::floor((eventTick - tickStartOfBar)/ ppq)) % timeSigNumerator + 1;
currentTick = static_cast<int> (eventTick) % ppq;
if (!message.isMetaEvent() && (currentTick == 0 || currentTick == 120 || currentTick == 240 || currentTick == 360)) {
std::stringstream ss;
ss << currentBar << ":" << currentBeat << ":" << setfill('0') << setw(3) << currentTick;
content->updateBbt(ss.str());
}
double origBpm = 60000 / (tickLength * ppq);
double delta = prevDelta + ((eventTick - prevTick) * (origBpm / currentBpm)) * tickLength;
Time::waitForMillisecondCounter(now + delta);
midiPort->sendMessageNow(message);
i++;
prevTick = eventTick;
prevDelta = delta;
}
delete midiPort;
return;
}
示例11: main
int main(int argc, char* argv[])
{
string printThis = ""; //string which will contain the content to be saved to output file
cout << "Path and name of file: ";
//String st = "C:\\Program Files (x86)\\Phase Shift\\music\\Paramore\\Paramore - Ignorance\\notes.mid"; //this file was throwing exceptions in Java version
//C:\Users\Sinead\Documents\102. Paramore 01_P-I\Paramore - Ignorance
// String st = "C:\\Users\\Sinead\\Documents\\102. Paramore 01_P-I\\Paramore - Ignorance\\notes.mid"; //hardcoded for now
String st = "C:\\Users\\Sinead\\Documents\\(GHSH_MSL)_09-TIO\\09 - Take It Off\\notes.mid"; //hardcoded for now
//String st = "C:\\Program Files (x86)\\Phase Shift\\music\\The Donnas\\09 - Take It Off\\notes.mid"; //hardcoded for now
//C:\\Users\\Sinead\\Documents\\(GHSH_MSL)_09-TIO\\09 - Take It Off
printThis += st.toStdString() + "\n";
cout << st << "\n";
//load notes.midi
File file(st);
FileInputStream fiStream(file);
MidiFile midiFile;
if (!midiFile.readFrom(fiStream))
{
cout << "Error: Nothing Loaded";
return 1;
}
if (midiFile.getNumTracks() == 0) return 1;
//set level of difficulty
string level = "expert"; //hardcoded for now
int lvl = 0;
if (level == "easy") {
lvl = 4;
}
else if (level == "medium") {
lvl = 5;
}
else if (level == "hard") {
lvl = 6;
}
else if (level == "expert") {
lvl = 7;
}
else {
cout << "invalid level";
return 1;
}
printThis += "Level: " + level + "\n";
//set instrument
string selectInstru = "drums";
if (selectInstru != "guitar" && selectInstru != "bass" && selectInstru != "drums" && selectInstru != "vocals")
{
cout << "invalid instrument";
return 1;
}
printThis += "Instrument: " + selectInstru + "\n";
long ticks_per_beat = midiFile.getTimeFormat();
int tracks = midiFile.getNumTracks();
int useTrack = 0; //the index of the mid file which contains the notes for the instrument. Set in following for-loop
string timeSig = ""; //the time signature of the song. Set in following for-loop
vector<vector<string>> songSections; //timestamps and sections names of the song. Set in following for-loop
//use this to store entries of [timestamp, song_section] which will be used to mark the verse, chorus, etc of the tab
//populated in the following for-loop
for (int n = 0; n < tracks; n++)
{
const MidiMessageSequence* seq = midiFile.getTrack(n);
MidiMessageSequence::MidiEventHolder * event = seq->getEventPointer(0); //get the event 0 for each track
MidiMessage m = event->message;
String trackName = m.getTextFromTextMetaEvent();
//TRACK WITH INSTRUMENT NOTES
if (trackName.toLowerCase().contains(String(selectInstru)))
//get indexes of the tracks which contain the songs sections, and drum notes
{
useTrack = n;
//cout << "use Track " << useTrack << "\n";
}
//TIME SIGNATURE
if (trackName.equalsIgnoreCase("midi_export"))
//get information about the song
//time signature and tempo are entries 2 and 3, where tick ==0
{
for (int nEvent = 1; nEvent < seq->getNumEvents(); nEvent++)
{
event = seq->getEventPointer(nEvent); //get each event in track
MidiMessage m = event->message;
double tick = m.getTimeStamp();
if (tick == 0)
{
//cout << n << " " << nEvent << " " << tick << " " << m.getTextFromTextMetaEvent() << "\n";
//cout << n << " " << nEvent << " isTimeSignatureMetaEvent " << m.isTimeSignatureMetaEvent () << " getTimeSignatureInfo \n"; //<< m.getTimeSignatureInfo() << "\n";
//getTimeSignatureInfo (int &numerator, int &denominator)
//cout << n << " " << nEvent << " isTempoMetaEvent " << m.isTempoMetaEvent () << " getTimeSignatureInfo \n"; //<< m.getTimeSignatureInfo() << "\n";
}
}
}
//.........这里部分代码省略.........
示例12: getTimestamp
const String getTimestamp(const MidiMessage &m)
{
return (String::formatted (" Time(%.6d)", m.getTimeStamp()));
}
示例13: main
//==============================================================================
int main (int argc, char* argv[])
{
if (argc != 3) {
cout << "Usage: <prog> <midi input file> <wav output file>" << endl;
return 0;
}
File inMidiFile = File(argv[1]);
File outWavFile = File(argv[2]);
//File inMidiFile = File("C:\\Users\\GeorgeKrueger\\Documents\\GitHub\\pymusic\\out.mid");
//File outWavFile = File("C:\\Users\\GeorgeKrueger\\Documents\\GitHub\\pymusic\\out.wav");
FileInputStream fileStream(inMidiFile);
juce::MidiFile midiFile;
midiFile.readFrom(fileStream);
int numTracks = midiFile.getNumTracks();
midiFile.convertTimestampTicksToSeconds();
std::cout << "Opened midi file: " << inMidiFile.getFileName() << " Tracks: " << numTracks << std::endl;;
playHead.posInfo.bpm = 120;
playHead.posInfo.isPlaying = true;
playHead.posInfo.timeInSamples = 0;
playHead.posInfo.timeInSeconds = 0;
playHead.posInfo.timeSigNumerator = 4;
playHead.posInfo.timeSigDenominator = 4;
for (int i = 0; i < numTracks; ++i)
{
const juce::MidiMessageSequence* msgSeq = midiFile.getTrack(i);
double trackLengthSeconds = 0;
String plugFile = "";
int program = 0;
for (int j = 0; j < msgSeq->getNumEvents(); ++j)
{
juce::MidiMessageSequence::MidiEventHolder* midiEventHolder = msgSeq->getEventPointer(j);
juce::MidiMessage midiMsg = midiEventHolder->message;
if (midiMsg.isMetaEvent() && midiMsg.getMetaEventType() == 0x04) {
// Instrument meta event
int instrLength = midiMsg.getMetaEventLength();
const juce::uint8* instrChars = midiMsg.getMetaEventData();
String instrName((char*)instrChars, instrLength);
plugFile = instrName;
}
if (midiMsg.isMetaEvent() && midiMsg.isEndOfTrackMetaEvent()) {
//int oetDataLength = midiMsg.getMetaEventLength();
//const uint8* oetData = midiMsg.getMetaEventData();
//std::cout << "Found end of track event data size: " << oetDataLength << " data: " << oetData << std::endl;
trackLengthSeconds = midiMsg.getTimeStamp();
std::cout << "Track length in seconds: " << trackLengthSeconds << std::endl;
}
}
if (trackLengthSeconds == 0) {
std::cerr << "Skipping track " << i << " since it has zero length" << std::endl;
continue;
}
if (plugFile.isEmpty()) {
plugFile = "C:\\VST\\helm.dll";
std::cout << "No plug found for track. Defaulting to: " << plugFile << std::endl;
//std::cerr << "Skipping track " << i << ". No instrument found." << std::endl;
//continue;
}
else {
std::cout << "Found plugin file '" << plugFile << "' from track " << i << std::endl;
}
OwnedArray<PluginDescription> results;
VSTPluginFormat vstFormat;
vstFormat.findAllTypesForFile(results, plugFile);
if (results.size() > 0) {
std::cout << "Found " << results.size() << " plugin(s) in file '" << plugFile << "'" << std::endl;
int blockSize = 1024;
double sampleRate = 44100;
int totalSizeInSamples = ((static_cast<int>(44100 * trackLengthSeconds) / 1024) + 1) * 1024;
cout << "Total samples to render " << totalSizeInSamples << endl;
juce::AudioPluginInstance* plugInst = vstFormat.createInstanceFromDescription(*results[0], sampleRate, blockSize);
if (!plugInst) {
cout << "Failed to load plugin " << plugFile << endl;
continue;
}
AudioProcessorGraph* graph = new AudioProcessorGraph();
graph->setPlayConfigDetails(0, 2, sampleRate, blockSize);
graph->setPlayHead(&playHead);
graph->addNode(plugInst, 1000);
int AUDIO_IN_ID = 101;
int AUDIO_OUT_ID = 102;
int MIDI_IN_ID = 103;
juce::AudioPluginInstance* audioInNode = new AudioGraphIOProcessor(AudioGraphIOProcessor::audioInputNode);
juce::AudioPluginInstance* audioOutNode = new AudioGraphIOProcessor(AudioGraphIOProcessor::audioOutputNode);
juce::AudioPluginInstance* midiInNode = new AudioGraphIOProcessor(AudioGraphIOProcessor::midiInputNode);
graph->addNode(audioInNode, AUDIO_IN_ID);
graph->addNode(audioOutNode, AUDIO_OUT_ID);
graph->addNode(midiInNode, MIDI_IN_ID);
//.........这里部分代码省略.........