Reputation: 845
I am trying to play an audio file but I can get it working.
I imported the AVFoundation
framework.
Here is the code:
NSString *fileName = [[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@"caf"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:fileName];
NSLog(@"Test: %@ ", url);
AVAudioPlayer *audioFile = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
audioFile.delegate = self;
audioFile.volume = 1;
[audioFile play];
I am receiving an error nil string parameter
I copied the file to the supporting files folder so the file is there.
Can you guys help me?
Thanks
Upvotes: 3
Views: 8378
Reputation: 677
Just follow two simple steps
Step1:
UIViewController.h
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
@property(nonatomic, retain) AVAudioPlayer *player;
Step 2:
UIViewController.m
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"sound"
ofType:@"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
[_player setVolume:1.0];
[_player play];
Just make sure AVAudioPlayer property must be nonatomic and retain.
Upvotes: 2
Reputation: 371
Make sure you import your audiotoolbox framework and then write the following. This is what I use to play simple sounds
#import <AudioToolbox/AudioToolbox.h>
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"Your sound here", CFSTR ("mp3"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
If you have any confusion with this let me know.
Upvotes: 0
Reputation: 3955
I use something like this when the file is in a specific folder:
// Build URL to the sound file we are going to play
NSURL *sound_file = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:sound_file_name ofType:@"mp3" inDirectory:directory]];
// Play it
audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL:sound_file error:nil];
audio_player.delegate = self;
[audio_player play];
[sound_file release];
sound_file_name
is the file name name without the extension: @"success"
directory
is something like: @"media/sound_effects"
Upvotes: 0
Reputation: 106
Add this and see if the program recognizes the file exists.
NSLog(@"File Exists:%d",[[NSFileManager defaultManager] fileExistsAtPath:fileName]);
It will print a 1 if it exists. If not make sure you have the proper filename (case matters).
Upvotes: 0