使用MusicPlayer播放midi文件&音乐序列

时间:2012-04-20 15:46:07

标签: ios objective-c midi audio-player coremidi

我使用以下代码成功地让iOS使用soundfont示例播放.mid(midi)文件:

-(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);
}

但是,当第一个文件仍在播放时我尝试播放第二个文件时出现问题。

我尝试了很多变化。首先,上面的代码将同时播放两个轨道。或者,我试过了:

DisposeMusicPlayer(musicPlayer);
DisposeMusicSequence(musicSequence);

NewMusicPlayer(&musicPlayer)之前,但这会产生一个奇怪版本的曲调,只播放零星的音符。

我很乐意简单地调用这种方法,然后播放下一首曲目。

1 个答案:

答案 0 :(得分:7)

好的,我找到了如何妥善处理MusicPlayerMusicSequence的答案。

-(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);
}