我想使用AV Foundation播放一个声音文件(我已经将其拖入Xcode并复制到项目中),但使用以下代码失败:
我认为NSURL *url = [[NSURL alloc] initWithString:@"sound.caf"];
这里出了问题,但除了这种方式,我不知道怎样用声音文件实例化AVAsset(当然,可能还有其他地方出错)。无论如何,有人能给我提供帮助吗?谢谢。
AVMutableComposition *composition = [AVMutableComposition composition];
CMPersistentTrackID trackID = kCMPersistentTrackID_Invalid;
AVMutableCompositionTrack *compositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:trackID];
NSURL *url = [[NSURL alloc] initWithString:@"sound.caf"];
AVAsset *songAsset = [AVURLAsset URLAssetWithURL:url options:nil];
AVAssetTrack *assetTrack = [[songAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
CMTime startTime = CMTimeMakeWithSeconds(0, 1);
CMTime endTime = songAsset.duration;
CMTimeRange tRange = CMTimeRangeMake(startTime, endTime);
NSError *error = nil;
[compositionTrack insertTimeRange:tRange ofTrack:assetTrack atTime:CMTimeMake(0, 44100) error:&error];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:composition];
self.player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[self.player play];