Reputation: 13
I was trying to play a song in iOS, but it gives me an error message.
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface PRPViewController : UIViewController{
AVAudioPlayer *audioPlayer;
IBOutlet UIButton *start;
}
-(IBAction)play;
@end
NSURL *url = [NSURL fileURLWithPath:
[NSString stringWithFormat:@"%@/bobmarley.mp3",
[[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsofURL:url error:&error];
audioPlayer.numberOfLoops = 0;
[audioPlayer play];
No visible @interface for AVAudioPlayer declares the selector 'initWithContentsofUrl:error:'
What should I do?
Upvotes: 0
Views: 886
Reputation: 6052
You should check if the file is available on your system with the method initWithContentsOfURL
, yours is written wrong. Otherwise the app can crash. I created a class which handles everything for me:
@implementation AudioPlayer{
AVAudioPlayer *_sound;
NSURL *_soundURL;
NSString *_receivedValue;
float _volumeSpecific;
}
- (id)initWithAudioFile:(NSString *)fileName andExtension:(NSString *)extension{
self = [super init];
if( self ){
_receivedValue = fileName;
_soundURL = [NSURL fileURLWithPath:
[[NSBundle mainBundle] pathForResource:fileName
ofType:extension]];
if([[NSFileManager defaultManager] fileExistsAtPath:[_soundURL path]]){
_sound = [[AVAudioPlayer alloc] initWithContentsOfURL:_soundURL
error:nil];
}
}
return self;
}
- (void)playEndless{
if( [[NSUserDefaults standardUserDefaults] boolForKey:kSound] ){
_sound.numberOfLoops = -1;
[_sound play];
}
}
- (void)setVolume:(float)myVolume{
_volumeSpecific = myVolume;
[_sound setVolume:myVolume];
}
- (void)play{
if( _sound == nil ){
NSLog(@"No AudioPlayer available %@", self);
}
if( [[NSUserDefaults standardUserDefaults] boolForKey:kSound] ){
if( _volumeSpecific ){
[_sound setVolume:_volumeSpecific];
}
[_sound play];
}
}
- (NSString *)description{
return [NSString stringWithFormat:@"Received: %@, Player: %@, URL: %@",
_receivedValue, _sound, _soundURL];
}
Upvotes: 0
Reputation: 534885
You should capitalize the "O" in Of
. In Objective-C, spelling counts, including capitalization. initWithContentsofURL
and initWithContentsOfURL
are two different things.
(By the way, this is a very good reason for using autocompletion as much as possible. The autocompletion mechanism knows much better than you do how to spell the names of the declared methods!)
Upvotes: 2