Search code examples
iphoneavaudiorecorderavplayeravurlassetavmutablecomposition

iPhone SdK: AVPlayer will not play a composition after adding a audio track


After adding an audio track (recorded with AVAudioRecorder) to a composition AVPlayer will not play it. AVPlayer.status = 1 and AVPlayer.error = null.

I have looked at the WWDC10 AVEdit demo code and it's pretty much similar. Could it be an audio format incompatibility?

the original composition allready contains a video and audio track from a video asset.

after removing the newly added audio track the player still does not play after removing the original audio track the player will play.

I'm also finding it hard to get debug information that would point me to the problem. If anyone has a suggestion it would be greatly appreciated.

Here is my code for adding the audio track

any help is most welcome

Jean-Pierre

-(void)editAudioViewController:(EditAudioViewController *)editAudioViewController didEditAudio:(NSURL *)url
{
[self dismissModalViewControllerAnimated:TRUE];

BOOL result;
NSError * error = nil;

if (url)
{
    AVURLAsset * asset = [AVURLAsset URLAssetWithURL:url options:nil] ;

    CMTimeRange audioTimeRange = CMTimeRangeMake(kCMTimeZero , asset.duration);
    if (CMTIME_COMPARE_INLINE(CMTimeRangeGetEnd(audioTimeRange), >, [composition duration]))
        audioTimeRange.duration = CMTimeSubtract([composition duration], audioTimeRange.start);

    AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio
                                    preferredTrackID:kCMPersistentTrackID_Invalid];

    AVAssetTrack *audioTrack = [asset compatibleTrackForCompositionTrack:compositionAudioTrack];

    result = [compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioTimeRange.duration) ofTrack:audioTrack atTime:audioTimeRange.start error:&error];

    if (!result)
    {
        NSLog(@"%@", [error description]);
    }

    [mp replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithAsset:composition]];
    [mp seekToTime:kCMTimeZero];

}
}

Solution

  • I had two separate sessions in my audio recorder code one for recording and one for playback. I switched to a single record/play session and this somehow fixed the problem:

    audioSession = [AVAudioSession sharedInstance];
    
    if (!audioSession.inputIsAvailable)
    {
        NSLog(@"No input available");
    }
    
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    
    NSError * error = nil;
    
    [audioSession setActive:TRUE error:&error];
    
    if (error)
    {
        NSLog(@"%@", [error description]);
    }