iOS - 如何使用AVFoundation播放音频文件

3

我想使用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];
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];

谢谢,Sergey,很方便找到这个。如果您正在CLI程序中尝试此操作系统X,则需要循环直到播放器完成。在开始播放后,我使用了以下循环:“do {CFRunLoopRunInMode(kCFRunLoopDefaultMode,0.25,false);} while(player.isPlaying);” - original_username

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接