使用AVPlayer播放AVMutableComposition时没有声音

时间:2015-08-14 13:16:46

标签: ios video avfoundation avplayer avmutablecomposition

我尝试创建一个AVMutableComposition并使用AVPlayer播放它。这就是我正在做的事情。

//定义AVComposition

self.composition = [[AVMutableComposition alloc] init];

//定义Mutable Track

self.mainVideoTrack = [self.composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

//定义资产

AVAsset *asset = [AVAsset assetWithURL:url];

//将资源插入曲目

[self.mainVideoTrack insertTimeRange:CMTimeRangeFromTimeToTime(CMTimeMake(0,1000),CMTimeMake(asset.duration*1000,1000)) ofTrack:[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:[self startingTimeForSegment:videoSegment] error:&error];

//使用合成

定义播放器项目
self.playerItem = [[AVPlayerItem alloc] initWithAsset:self.composition];

//定义播放器,播放器层&添加图层

self.avPlayer = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
self.layerVideo = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
self.layerVideo.frame = self.previewContainer.bounds;
[self.previewContainer.layer addSublayer:self.layerVideo];

但是我听不到播放器层中的声音。如果我直接使用资产初始化播放项目而不使用AVMutableComposition,它会播放声音。我究竟做错了什么?坚持这个。

1 个答案:

答案 0 :(得分:2)

看起来您只向AVMutableComposition添加了一首曲目。您还需要从资产中添加音频轨道。这可以与添加视频轨道完全相同。

self.mainAudioTrack = [self.composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

然后您可以从资源中插入音轨。这假设您希望音频从视频所在的同一点开始。

[self.mainAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero,asset.duration) ofTrack:[[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:[self startingTimeForSegment:audio] error:&error];
相关问题