iOS - how to play sound file using avfoundation

2.4k views Asked by At

I want to play a sound file (which I have dragged into xcode and copy to the project) using av foundation with the following code but fail.

I think NSURL *url = [[NSURL alloc] initWithString:@"sound.caf"]; this is where it goes wrong, but I have no idea other than this way, how I could instantiate an AVAsset with this the sound file (of course, it would be other place that goes wrong). Anyway, can someone offer me some helps? thanks

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

There are 2 answers

1
Sergey Demchenko On

This code should help you:

    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];
0
Shyam Dixit On

Try this

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