How to program a real-time accurate audio sequencer on the iphone?

后端 未结 9 608
北荒
北荒 2021-01-30 02:56

I want to program a simple audio sequencer on the iphone but I can\'t get accurate timing. The last days I tried all possible audio techniques on the iphone, starting from Audio

9条回答
  •  时光说笑
    2021-01-30 03:16

    If constructing your sequence ahead of time is not a limitation, you can get precise timing using an AVMutableComposition. This would play 4 sounds evenly spaced over 1 second:

    // setup your composition
    
    AVMutableComposition *composition = [[AVMutableComposition alloc] init];
    NSDictionary *options = @{AVURLAssetPreferPreciseDurationAndTimingKey : @YES};
    
    for (NSInteger i = 0; i < 4; i++)
    {
      AVMutableCompositionTrack* track = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
      NSURL *url = [[NSBundle mainBundle] URLForResource:[NSString stringWithFormat:@"sound_file_%i", i] withExtension:@"caf"];
      AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:options];
      AVAssetTrack *assetTrack = [asset tracksWithMediaType:AVMediaTypeAudio].firstObject;
      CMTimeRange timeRange = [assetTrack timeRange];
    
      Float64 t = i * 1.0;
      NSError *error;
      BOOL success = [track insertTimeRange:timeRange ofTrack:assetTrack atTime:CMTimeMake(t, 4) error:&error];
      NSAssert(success && !error, @"error creating composition");
    }
    
    AVPlayerItem* playerItem = [AVPlayerItem playerItemWithAsset:composition];
    self.avPlayer = [[AVPlayer alloc] initWithPlayerItem:playerItem];
    
    // later when you want to play 
    
    [self.avPlayer seekToTime:kCMTimeZero];
    [self.avPlayer play];
    

    Original credit for this solution: http://forum.theamazingaudioengine.com/discussion/638#Item_5

    And more detail: precise timing with AVMutableComposition

提交回复
热议问题