iOS - 如何使用avfoundation播放声音文件

时间:2013-09-11 12:20:10

标签: ios avplayer avasset avcomposition

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

我认为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 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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];