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.

madLokesh
  • 1,860
  • 23
  • 49
ilikejames
  • 121
  • 1
  • 8
  • i followed your code snippet and the tutorial here http://www.deluge.co/?q=comment/477#comment-477 but no output there. could you please help me to play a mid file – makboney Aug 19 '14 at 05:37

1 Answers1

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);
}
ilikejames
  • 121
  • 1
  • 8
  • Shouldn't that be `MusicSequenceGetIndTrack (musicSequence, i, &track);` (replace "0" with "i") ? – Olie Apr 11 '13 at 17:07
  • 1
    In my experience with MusicPlayer, I just switched MusicSequences - didn't need to dispose of the player instance. – spring Aug 02 '13 at 13:05