3

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];
vincentzvegaz
  • 175
  • 1
  • 7
Newbie
  • 2,775
  • 6
  • 33
  • 40

2 Answers2

2

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];
Sergey Demchenko
  • 2,924
  • 1
  • 24
  • 26
  • Thank you, Sergey, very convenient to find this. If you're trying this on OS X in a CLI program, you need to loop until the player has finished. I used the following loop, after starting playback: "do { CFRunLoopRunInMode ( kCFRunLoopDefaultMode, 0.25, false ); } while ( player.isPlaying );" – original_username Mar 11 '14 at 00:00
1

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];
Fattie
  • 27,874
  • 70
  • 431
  • 719
Shyam Dixit
  • 2,325
  • 3
  • 19
  • 27