我想使用带有以下代码的av基础播放声音文件(已将其拖放到xcode中并复制到项目中),但失败了。

我认为NSURL *url = [[NSURL alloc] initWithString:@"sound.caf"];这是出问题的地方,但是除了这种方式,我别无选择,如何用此声音文件实例化AVAset(当然,这是其他地方出了问题)。无论如何,有人可以给我一些帮助吗?谢谢

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];

最佳答案

此代码应帮助您:

    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"wav"];
    NSURL *soundURL = [NSURL fileURLWithPath:soundPath];

    NSError *error = nil;
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];

    if (error) {
        NSLog(@"%@",[error localizedDescription]);
    }

    [player play];

10-08 08:46