3

我想使用带有以下代码的av基础播放声音文件(我已将其拖入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];
4

2 回答 2

2

此代码应该可以帮助您:

    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];
于 2013-09-11T12:28:41.143 回答
1

尝试这个

NSString *shutterplayerPath =
  [[NSBundle mainBundle] pathForResource:@"shutter" ofType:@"mp3"];
NSString *tickplayerPath =
  [[NSBundle mainBundle] pathForResource:@"tick" ofType:@"wav"];
shutterAudioPlayer = 
  [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSURL alloc]
initFileURLWithPath: shutterplayerPath] error:NULL];
tickAudioPlayer =
  [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSURL alloc];
initFileURLWithPath:tickplayerPath] error:NULL];
[shutterAudioPlayer play];
[tickAudioPlayer play];
于 2013-09-11T12:47:14.743 回答