Playing midi files with MusicPlayer & Music Sequence
Asked Answered
S

1

5

I've successfully gotten iOS to play a .mid (midi) file with a soundfont sample using the following code:

-(void) playMusic:(NSString*) name
{
    NSString *presetURLPath = [[NSBundle mainBundle] pathForResource:@"GortsMiniPianoJ1" ofType:@"SF2"];
    NSURL * presetURL = [NSURL fileURLWithPath:presetURLPath]; 
    [self loadFromDLSOrSoundFont: (NSURL *)presetURL withPatch: (int)3];

    NSString *midiFilePath = [[NSBundle mainBundle] pathForResource:name ofType:@"mid"];
    NSURL * midiFileURL = [NSURL fileURLWithPath:midiFilePath];

    NewMusicPlayer(&musicPlayer);

    if (NewMusicSequence(&musicSequence) != noErr) 
    {
        [NSException raise:@"play" format:@"Can't create MusicSequence"];  
    }

    if(MusicSequenceFileLoad(musicSequence, (CFURLRef)midiFileURL, 0, 0 != noErr)) 
    {
        [NSException raise:@"play" format:@"Can't load MusicSequence"];
    }

    MusicPlayerSetSequence(musicPlayer, musicSequence);
    MusicSequenceSetAUGraph(musicSequence, _processingGraph);
    MusicPlayerPreroll(musicPlayer);
    MusicPlayerStart(musicPlayer);
}

However, the problem comes when I then try to play a second file when the first is still playing.

I've tried many variations. Firstly, the above code will play both tracks simultaneously. Or, I've tried:

DisposeMusicPlayer(musicPlayer);
DisposeMusicSequence(musicSequence);

Before the NewMusicPlayer(&musicPlayer), but this produces a weird version of the tune with only sporadic notes being played.

I'd love to simply call this method, and the next track to be played.

Subtract answered 20/4, 2012 at 15:46 Comment(1)
i followed your code snippet and the tutorial here deluge.co/?q=comment/477#comment-477 but no output there. could you please help me to play a mid fileTurncoat
S
7

Ok, I found the answer on how to properly dispose of a MusicPlayer and MusicSequence.

-(void) stop
{
   OSStatus result = noErr;

   result = MusicPlayerStop(musicPlayer);

   UInt32 trackCount;
   MusicSequenceGetTrackCount(musicSequence, &trackCount);

   MusicTrack track;
   for(int i=0;i<trackCount;i++)
   {
      MusicSequenceGetIndTrack (musicSequence, i, &track);
      result = MusicSequenceDisposeTrack(musicSequence, track);
   }

   result = DisposeMusicPlayer(musicPlayer);
   result = DisposeMusicSequence(musicSequence);
   result = DisposeAUGraph(_processingGraph);
}
Subtract answered 11/5, 2012 at 10:8 Comment(2)
Shouldn't that be MusicSequenceGetIndTrack (musicSequence, i, &track); (replace "0" with "i") ?Jingoism
In my experience with MusicPlayer, I just switched MusicSequences - didn't need to dispose of the player instance.Kristine

© 2022 - 2024 — McMap. All rights reserved.