Unable to hear sound in iOS - ios

In my app I've having trouble to hear a sound. In particular this is my code:
#import <QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ViewController.h"
#import "RIOInterface.h"
#import "KeyHelper.h"
#import "Toast+UIView.h"
#interface ViewController () {
BOOL watermarkReceived;
float frequencyRecived;
CABasicAnimation *theAnimation;
BOOL water1, water2, water3, water4, noWater;
}
#property(nonatomic)NSTimer *timer, *timer2;
#property(nonatomic,strong)AVAudioPlayer *player;
#property(nonatomic,strong)NSURL *url;
#end
#implementation ViewController
#synthesize isListening;
#synthesize rioRef;
#synthesize currentFrequency;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//self.labelPosition.font=[UIFont fontWithName:#"DBLCDTempBlack" size:20.0];
NSError *error;
self.url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"sms_alert_circles" ofType:#"mp3"]];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.rioRef = [RIOInterface sharedInstance];
[rioRef setSampleRate:44100];
[rioRef setFrequency:394];//294
[rioRef initializeAudioSession];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startListenWatermark:(UIButton *)sender {
if ([sender isSelected]) {
[self stopListener];
[UIApplication sharedApplication].idleTimerDisabled = NO;
[sender setSelected:NO];
[self.imageListening.layer removeAllAnimations];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
//self.labelPosition.font=[UIFont fontWithName:#"DBLCDTempBlack" size:20.0];
self.labelPosition.text = #"Nessuna postazione";
} else {
water1 = water2 = water3 = water4 = NO;
[self startListener];
[UIApplication sharedApplication].idleTimerDisabled = YES;
[sender setSelected:YES];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.labelPosition.text = #"Nessuna postazione";
theAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
theAnimation.duration = 0.4;
theAnimation.repeatDuration = 10000;
theAnimation.autoreverses = YES;
theAnimation.delegate = self;
theAnimation.fromValue = [NSNumber numberWithFloat:1.0];
theAnimation.toValue = [NSNumber numberWithFloat:0.1];
[self.imageListening.layer addAnimation:theAnimation forKey:#"animateOpacity"];
}
}
#pragma mark Listener methods
- (void)startListener {
[self.rioRef startListening:self];
}
- (void)stopListener {
[self.rioRef stopListening];
}
- (void)frequencyChangedWithValue:(float)newFrequency {
frequencyRecived = newFrequency;
watermarkReceived = YES;
if (frequencyRecived > 18000) {
if (frequencyRecived >= 18000 && frequencyRecived <= 18110 && !water1) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"1" waitUntilDone:YES];
water2 = water3 = water4 = NO;
water1 = YES;
noWater = YES;
}
if (frequencyRecived >= 18115 && frequencyRecived <= 18250 && !water2) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"2" waitUntilDone:YES];
water1 = water3 = water4 = NO;
water2 = YES;
noWater = YES;
}
if (frequencyRecived >= 18255 && frequencyRecived <= 18440 && !water3) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"3" waitUntilDone:YES];
water1 = water2 = water4 = NO;
water3 = YES;
noWater = YES;
}
if (frequencyRecived >= 18445 && !water4) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"4" waitUntilDone:YES];
water1 = water2 = water3 = NO;
water4 = YES;
noWater = YES;
}
} else {
if (noWater) {
[self performSelectorOnMainThread:#selector(noWatermark) withObject:nil waitUntilDone:YES];
noWater = NO;
}
}
}
- (void)noWatermark {
self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(noPosition:) userInfo:nil repeats:NO];
}
- (void)noPosition:(NSTimer*)aTimer {
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"Nessuna postazione" waitUntilDone:YES];
[self performSelectorInBackground:#selector(redLed) withObject:nil];
self.timer2 = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(resetFlags) userInfo:nil repeats:NO];
}
- (void)resetFlags {
water1 = water2 = water3 = water4 = NO;
}
- (void)redLed {
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
}
- (void)setTextInLabel:(NSString*)position {
[self.timer invalidate];
self.timer = nil;
if ([position isEqualToString:#"Nessuna postazione"]) {
self.labelPosition.text = position;
}
self.labelPosition.text = position;
if (![position isEqualToString:#"Nessuna postazione"]) {
[self.player setVolume:1.0];
[self.player prepareToPlay];
[self.player play];
NSString *textForToast = [NSString stringWithFormat:#"Postazione %#", position];
UIImage *image = [[UIImage alloc]init];
if ([position isEqualToString:#"1"]) {
image = [UIImage imageNamed:#"image_smart.png"];
}
if ([position isEqualToString:#"2"]) {
image = [UIImage imageNamed:#"image_500.png"];
}
if ([position isEqualToString:#"3"]) {
image = [UIImage imageNamed:#"image_mini.png"];
}
if ([position isEqualToString:#"4"]) {
image = [UIImage imageNamed:#"image_aygo.png"];
}
[self.view makeToast:textForToast duration:5.0 position:#"bottom" title:#"Watermark ricevuto" image:image];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_green.png"]];
}
}
#end
In particular, this class should hear (with microphone) an audio signal in which there are some tone with a frequency >= 18000 Hz. So I will make this: when it recognize a tone of a frequency >= 18000 Hz it should play a sound.
When I try to run the app on the device I hear the sound with a very low volume by using iPhone speaker, but when I plug the headphone I hear the sound with an high volume. I tried to run the app by using simulator and when I use simulator it works nice. Why's that? Can you help me to fix this class?
PS: to detect the frequency of sounds I'm using pitch detector.

I solved it, I post here the code:
#import <QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ViewController.h"
#import "RIOInterface.h"
#import "KeyHelper.h"
#import "Toast+UIView.h"
#interface ViewController () {
BOOL watermarkReceived;
float frequencyRecived;
CABasicAnimation *theAnimation;
BOOL water1, water2, water3, water4, noWater;
}
#property(nonatomic)NSTimer *timer, *timer2;
//#property(strong)AVAudioPlayer *player;
#property(nonatomic,strong)NSURL *url;
#end
#implementation ViewController
#synthesize isListening;
#synthesize rioRef;
#synthesize currentFrequency;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// NSError *error;
//
// self.url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"sms_alert_circles" ofType:#"mp3"]];
// player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
//
// AVAudioSession *session = [AVAudioSession sharedInstance];
//
// NSError *setCategoryError = nil;
// [session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.rioRef = [RIOInterface sharedInstance];
[rioRef setSampleRate:44100];
[rioRef setFrequency:394];//294
[rioRef initializeAudioSession];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startListenWatermark:(UIButton *)sender {
if ([sender isSelected]) {
[self stopListener];
[UIApplication sharedApplication].idleTimerDisabled = NO;
[sender setSelected:NO];
[self.imageListening.layer removeAllAnimations];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
//self.labelPosition.font=[UIFont fontWithName:#"DBLCDTempBlack" size:20.0];
self.labelPosition.text = #"Nessuna postazione";
} else {
water1 = water2 = water3 = water4 = NO;
[self startListener];
[UIApplication sharedApplication].idleTimerDisabled = YES;
[sender setSelected:YES];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.labelPosition.text = #"Nessuna postazione";
theAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
theAnimation.duration = 0.4;
theAnimation.repeatDuration = 10000;
theAnimation.autoreverses = YES;
theAnimation.delegate = self;
theAnimation.fromValue = [NSNumber numberWithFloat:1.0];
theAnimation.toValue = [NSNumber numberWithFloat:0.1];
[self.imageListening.layer addAnimation:theAnimation forKey:#"animateOpacity"];
}
}
#pragma mark Listener methods
- (void)startListener {
[self.rioRef startListening:self];
}
- (void)stopListener {
[self.rioRef stopListening];
}
- (void)frequencyChangedWithValue:(float)newFrequency {
frequencyRecived = newFrequency;
watermarkReceived = YES;
if (frequencyRecived > 18000) {
if (frequencyRecived >= 18000 && frequencyRecived <= 18110 && !water1) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"1" waitUntilDone:YES];
water2 = water3 = water4 = NO;
water1 = YES;
noWater = YES;
}
if (frequencyRecived >= 18115 && frequencyRecived <= 18250 && !water2) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"2" waitUntilDone:YES];
water1 = water3 = water4 = NO;
water2 = YES;
noWater = YES;
}
if (frequencyRecived >= 18255 && frequencyRecived <= 18440 && !water3) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"3" waitUntilDone:YES];
water1 = water2 = water4 = NO;
water3 = YES;
noWater = YES;
}
if (frequencyRecived >= 18445 && !water4) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"4" waitUntilDone:YES];
water1 = water2 = water3 = NO;
water4 = YES;
noWater = YES;
}
} else {
if (noWater) {
[self performSelectorOnMainThread:#selector(noWatermark) withObject:nil waitUntilDone:YES];
noWater = NO;
}
}
}
- (void)noWatermark {
self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(noPosition:) userInfo:nil repeats:NO];
}
- (void)noPosition:(NSTimer*)aTimer {
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"Nessuna postazione" waitUntilDone:YES];
[self performSelectorInBackground:#selector(redLed) withObject:nil];
self.timer2 = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(resetFlags) userInfo:nil repeats:NO];
}
- (void)resetFlags {
water1 = water2 = water3 = water4 = NO;
}
- (void)redLed {
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
}
- (void)setTextInLabel:(NSString*)position {
[self.timer invalidate];
self.timer = nil;
NSError *error;
self.url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"sms_alert_circles" ofType:#"mp3"]];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
if ([position isEqualToString:#"Nessuna postazione"]) {
self.labelPosition.text = position;
}
self.labelPosition.text = position;
if (![position isEqualToString:#"Nessuna postazione"]) {
[player setVolume:1.0];
[player prepareToPlay];
[player play];
NSString *textForToast = [NSString stringWithFormat:#"Postazione %#", position];
UIImage *image = [[UIImage alloc]init];
if ([position isEqualToString:#"1"]) {
image = [UIImage imageNamed:#"image_smart.png"];
}
if ([position isEqualToString:#"2"]) {
image = [UIImage imageNamed:#"image_500.png"];
}
if ([position isEqualToString:#"3"]) {
image = [UIImage imageNamed:#"image_mini.png"];
}
if ([position isEqualToString:#"4"]) {
image = [UIImage imageNamed:#"image_aygo.png"];
}
[self.view makeToast:textForToast duration:5.0 position:#"bottom" title:#"Watermark ricevuto" image:image];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_green.png"]];
}
}
#end
I just put the initializer of the AVAudioPlayer into method setTextInLabel and it works.
Thank you!

Related

how to call the function to display the data in objective-c

I am creating the app for kids.I am new to this field.
The below code is for speech:
-(void)textToSpeechAction:(NSMutableArray *)imageStoreArray :(int)counter :(UIImageView *)imageChangeImageView :(UIImageView *)spekerOrMic :(BOOL)isMicPresent
{
spekerOrMic.image = [UIImage imageNamed:#"speaker.png"];
NSArray *items = [[imageStoreArray objectAtIndex:counter] componentsSeparatedByString:#"."];
NSString *speechString;
if(_isWritePresent)
{
NSArray *viewToRemove = [spekerOrMic subviews];
for (UIImageView *v in viewToRemove) {
[v removeFromSuperview];
}
spekerOrMic.image = [UIImage imageNamed:#""];
spekerOrMic.backgroundColor = [UIColor colorWithRed:41/255.0 green:52/255.0 blue:44/255.0 alpha:1.0];
NSString *tempString = [items objectAtIndex:0];
NSArray *tempArray = [tempString componentsSeparatedByString:#" "];
speechString = [tempArray objectAtIndex:1];
}
else
{
speechString = [items objectAtIndex:0];
}
AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc]init];
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:speechString];
[utterance setRate:0.2f];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:#"en-US"];
[synthesizer speakUtterance:utterance];
imageChangeImageView.image = [UIImage imageNamed:[imageStoreArray objectAtIndex:counter]];
if(isMicPresent)
{
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(micAction:) userInfo:spekerOrMic repeats:NO];
}
}
-(void)micAction:(NSTimer *)timer
{
NSLog(#"mic action");
UIImageView *micOrSpeaker = timer.userInfo ;
micOrSpeaker.image = [UIImage imageNamed:#"mic.png"];
// Set the audio file
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
[recorder record];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(recordStopAction:) userInfo:micOrSpeaker repeats:NO];
}
-(void)recordStopAction:(NSTimer *)timer
{
NSLog(#"stop");
[recorder stop];
UIImageView *micOrSpeaker = timer.userInfo;
micOrSpeaker.image = [UIImage imageNamed:#""];
_isRecordComplete = YES;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setActive:NO error:nil];
}
-(void)recordPlayAction
{
if (!recorder.recording){
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
[_player setDelegate:self];
[_player play];
}
}
alphabet phonics code:
NSMutableArray *arrForA = [[NSMutableArray alloc] initWithObjects:#"apple.png", #"ant.png", nil];
NSMutableArray *arrForB = [[NSMutableArray alloc] initWithObjects:#"bee.png", #"bear.png", nil];
dictAlpha = [[NSMutableDictionary alloc] initWithObjectsAndKeys: arrForA, #"a.png", arrForB,#"b.png", nil];
NSLog(#"%#",dictAlpha); // 1
commonFunctionObject = [[SpeechCommonFunctions alloc]init];
commonFunctionObject.isRecordComplete = NO;
counter = 0;
isMicPresent = YES;
_confirmationPopupView.hidden = true;
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(repeatActionFire) userInfo:nil repeats:NO];
}
-(void)repeatActionFire
{
keys=[dictAlpha allKeys];
if(counter>=keys.count)
{
NSLog(#"finished");
[_alphabetsShowImageView removeFromSuperview];
[_speakerOrMicImageView removeFromSuperview];
[_images removeFromSuperview];
UIImageView *congratzView = [[UIImageView alloc]initWithFrame:self.view.frame];
congratzView.image = [UIImage imageNamed:#"congratulation.png"];
[self.view addSubview:congratzView];
}
else{
[commonFunctionObject textToSpeechAction:keys :counter :_alphabetsShowImageView:_speakerOrMicImageView :isMicPresent];
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(ActionToCkeckRecordCompletion) userInfo:nil repeats:NO];
}
}
-(void)pik{
arrVal = [dictAlpha objectForKey:keys[i]];
if(j<arrVal.count){
[commonFunctionObject textToSpeechAction:arrVal :j :_images :_speakerOrMicImageView :isMicPresent];
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(ActionToCkeckRecordCompletion1) userInfo:nil repeats:NO];
}
else
{
// [arrVal removeAllObjects];
[_images removeFromSuperview];
counter+=1;
[self repeatActionFire];
}
}
-(void)ActionToCkeckRecordCompletion1
{
if(commonFunctionObject.isRecordComplete)
{
_confirmationPopupView.hidden = false;
}
[self pik];
}
-(void)ActionToCkeckRecordCompletion
{
if(commonFunctionObject.isRecordComplete)
{
_confirmationPopupView.hidden = false;
}
[self pik];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)playButtonAction:(id)sender
{
[commonFunctionObject recordPlayAction];
}
- (IBAction)nextButtonAction:(id)sender
{
j+=1;
[self pik];
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
- (IBAction)retryButtonAction:(id)sender
{
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
In alphabet phonics code ,i need to modify the code.
According the code my output is getting as :
first it display the a.png image then apple image then ant image then b.png image but bat image is not displaying .how to do?

how to display the congratulation view in iPhone using objective -c

I am developing a learning app for preschool kids. This is my code:
numbersStoreArray = [[NSMutableArray alloc]initWithObjects:#"1.png",#"2.png",#"3.png",#"4.png",#"5.png",#"6.png",#"7.png",#"8.png",#"9.png",#"10.png", nil];
commonFunctionObject = [[SpeechCommonFunctions alloc]init];
commonFunctionObject.isRecordComplete = NO;
counter = 0;
isMicPresent = YES;
_confirmationPopupView.hidden = true;
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(repeatActionFire) userInfo:nil repeats:NO];
}
-(void)repeatActionFire
{
if(counter >= numbersStoreArray.count)
{
NSLog(#"finished");
[_numbersShowImageView removeFromSuperview];
[_speakerOrMicImageView removeFromSuperview];
UIImageView *congratzView = [[UIImageView alloc]initWithFrame:self.view.frame];
congratzView.image = [UIImage imageNamed:#""];
[self.view addSubview:congratzView];
}
else
{
[commonFunctionObject textToSpeechAction:numbersStoreArray :counter :_numbersShowImageView :_speakerOrMicImageView :isMicPresent];
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(ActionToCkeckRecordCompletion) userInfo:nil repeats:YES];
}
}
-(void)ActionToCkeckRecordCompletion
{
if(commonFunctionObject.isRecordComplete)
{
_confirmationPopupView.hidden = false;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)playButtonAction:(id)sender
{
[commonFunctionObject recordPlayAction];
}
- (IBAction)nextButtonAction:(id)sender
{
counter+=1;
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
- (IBAction)retryButtonAction:(id)sender
{
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
After completion of this, this entry to the repeatActionFire and show finished. My question is: I need to display the congratulation view after the completion of the game and need to use two buttons.
Buttons for:
to reach the homepage
to retry the game.
How to do this?

Expected identifier on if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)

*This is the whole code :)
I have been trying to fix this for an hour now, but i can still not make it.
I would be happy if someone could help me :)
Still can't make the UI_USER_INTERFACE_IDIOM code work.*
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(void)Collision{
if (CGRectIntersectsRect(Heli.frame, Obstacle.frame)) {
[self EndGame];
}
if (CGRectIntersectsRect(Heli.frame, Obstacle2.frame)) {
[self EndGame];
}
if (CGRectIntersectsRect(Heli.frame, Bottom1.frame)) {
[self EndGame];
}
if (CGRectIntersectsRect(Heli.frame, Top1.frame)) {
[self EndGame];
}
}
-(void)EndGame{
if (Scorenumber > HighScore) {
HighScore = Scorenumber;
[[NSUserDefaults standardUserDefaults] setInteger:HighScore
forKey:#"HighScoreSaved"];
}
Heli.hidden = YES;
[timer invalidate];
[Scorer invalidate];
[self performSelector:#selector(NewGame) withObject: nil afterDelay:2];
}
-(void)NewGame{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
// For iPhone
Bottom1.hidden = YES;
Top1.hidden = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
corona.hidden = YES;
Intro1.hidden = NO;
Intro2.hidden = NO;
Intro3.hidden = NO;
Heli.hidden = NO;
Heli.center = CGPointMake(88, 286);
Heli.image = [UIImage imageNamed:#"buss til app opp.png"];
Start = YES;
Scorenumber = 0;
Score.text = [NSString stringWithFormat:#"Score: 0"];
Intro3.text = [NSString stringWithFormat:#"HighScore: %i", HighScore];
}
} else{
// For iPad
Bottom1.hidden = YES;
Top1.hidden = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
corona.hidden = YES;
Intro1.hidden = NO;
Intro2.hidden = NO;
Intro3.hidden = NO;
Heli.hidden = NO;
Heli.center = CGPointMake(153, 515);
Heli.image = [UIImage imageNamed:#"buss til app opp.png"];
Start = YES;
Scorenumber = 0;
Score.text = [NSString stringWithFormat:#"Score: 0"];
Intro3.text = [NSString stringWithFormat:#"HighScore: %i", HighScore];
Just look at following code:
-(void)NewGame{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
// For iPhone
Bottom1.hidden = YES;
Top1.hidden = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
corona.hidden = YES;
Intro1.hidden = NO;
Intro2.hidden = NO;
Intro3.hidden = NO;
Heli.hidden = NO;
Heli.center = CGPointMake(88, 286);
Heli.image = [UIImage imageNamed:#"buss til app opp.png"];
Start = YES;
Scorenumber = 0;
Score.text = [NSString stringWithFormat:#"Score: 0"];
Intro3.text = [NSString stringWithFormat:#"HighScore: %i", HighScore];
}
} else{
and see - "}" symbol on line before "} else{" is wrong. It is the pair for
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
opening construction, so "else" is "standalone - it is wrong.
Try to delete this "}".

Start an action after timer

In my iOS app I've to do an action after a delay. I will explain it better: my app can recognize some audio frequency:
18100 Hz
18200 Hz
18300 Hz
18500 Hz
To do that I've modified the pitch detector. I want to start a timer when the device doesn't recognize one of the frequency that I've setter up in my app.
I made so:
- (void)frequencyChangedWithValue:(float)newFrequency {
frequencyRecived = newFrequency;
watermarkReceived = YES;
if (frequencyRecived > 18000) {
if (frequencyRecived >= 18000 && frequencyRecived <= 18110 && !water1) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"1"];
water2 = water3 = water4 = NO;
water1 = YES;
}
if (frequencyRecived >= 18115 && frequencyRecived <= 18250 && !water2) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"2"];
water1 = water3 = water4 = NO;
water2 = YES;
}
if (frequencyRecived >= 18255 && frequencyRecived <= 18440 && !water3) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"3"];
water1 = water2 = water4 = NO;
water3 = YES;
}
if (frequencyRecived >= 18450 && !water4) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"4"];
water1 = water2 = water3 = NO;
water4 = YES;
}
} else {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"Nessuna postazione"];
water1 = water2 = water3 = water4 = NO;
}
}
In the else section I've to start a timer that it count for 10 seconds, after this time I've to write a label. I tried to use the following solution:
[self performSelector:<#(SEL)#> withObject:<#(id)#> afterDelay:<#(NSTimeInterval)#> inModes:<#(NSArray *)#>]
, but it never call the selector method because every time the app execute the code in else it restart the timer.
Can you suggest me a solution to solve this issue?
Thanks
UPDATE
I follow the answer, but it doesn't work. I post here the code updated:
#interface ViewController () {
BOOL watermarkReceived;
float frequencyRecived;
CABasicAnimation *theAnimation;
BOOL water1, water2, water3, water4;
}
#property(nonatomic,strong)NSTimer *timer;
#end
- (void)frequencyChangedWithValue:(float)newFrequency {
frequencyRecived = newFrequency;
watermarkReceived = YES;
if (frequencyRecived > 18000) {
[self.timer invalidate];
self.timer = nil;
if (frequencyRecived >= 18000 && frequencyRecived <= 18110 && !water1) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"1"];
water2 = water3 = water4 = NO;
water1 = YES;
}
if (frequencyRecived >= 18115 && frequencyRecived <= 18250 && !water2) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"2"];
water1 = water3 = water4 = NO;
water2 = YES;
}
if (frequencyRecived >= 18255 && frequencyRecived <= 18440 && !water3) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"3"];
water1 = water2 = water4 = NO;
water3 = YES;
}
if (frequencyRecived >= 18450 && !water4) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"4"];
water1 = water2 = water3 = NO;
water4 = YES;
}
} else {
self.timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(noPosition) userInfo:nil repeats:NO];
// [self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"Nessuna postazione"];
water1 = water2 = water3 = water4 = NO;
}
}
- (void)noPosition {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"Nessuna postazione"];
}
PS: I understood the other problems you told me and I will solve in the future, for now I need to fix the timer issue. :)
Use an NSTimer. In the else branch, check if the timer already exists and, if not, create and schedule it. In the main branch of the if, invalidate and destroy the timer.
Also, your if statement has a number of holes and is overly complex. You have already checked that the frequency is > 18000 so you don't need to check it again. You are also using if, else if to simplify because each is a distinct range, and if one range is detected then none of the other ranges can be. In this way you can just check that the upper range bound is not exceeded in the inner if.
Also, setting the text in the background looks wrong. UI updates need to be made from the main thread
Something like:
- (void)frequencyChangedWithValue:(float)newFrequency {
frequencyRecived = newFrequency;
watermarkReceived = YES;
if (frequencyRecived > 18000) {
[self.timer invalidate];
self.timer = nil;
if (frequencyRecived <= 18110) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"1"];
water2 = water3 = water4 = NO;
water1 = YES;
}
else if (frequencyRecived <= 18250) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"2"];
water1 = water3 = water4 = NO;
water2 = YES;
}
else if (frequencyRecived <= 18440) {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"3"];
water1 = water2 = water4 = NO;
water3 = YES;
}
else {
[self performSelectorInBackground:#selector(setTextInLabel:) withObject:#"4"];
water1 = water2 = water3 = NO;
water4 = YES;
}
} else {
if (self.timer == nil) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:... target:self selector:... userInfo:nil repeats:NO];
}
water1 = water2 = water3 = water4 = NO;
}
}

AVAudioRecorder and AVAudioPlayer

It's day three and I still can't get playback. I've been following the few tutorials on AVAudioPlayer/AVAudioRecorder. Using NSFileManager it looks like a file is created, but no dice still on that playback.
RecorderViewController.m
// RecorderViewController.m
// AudioTest
//
#import "RecorderViewController.h"
#import <Foundation/Foundation.h>
#interface RecorderViewController ()
#end
#implementation RecorderViewController
#synthesize userIsRecording, filePath, activityView, recordButton, playButton, recorder;
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
+ (CGRect)makeCGRectWithCenter:(CGPoint)center width:(float)width height:(float)height
{
return CGRectMake(center.x-width/2, center.y-height/2, width, height);
}
#pragma mark - Preparation
- (void)loadView
{
// RECORD BUTTON
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.recordButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.recordButton.frame = [[self class] makeCGRectWithCenter:CGPointMake(self.view.frame.size.width/2, 100) width:150 height:50];
[self.recordButton setTitle:#"Record" forState:UIControlStateNormal];
[self.recordButton addTarget:self action:#selector(recordPressed) forControlEvents:UIControlEventTouchUpInside];
// PLAY BUTTON
self.playButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.playButton.frame = [[self class] makeCGRectWithCenter:CGPointMake(self.view.frame.size.width/2, 200) width:150 height:50];
[self.playButton setTitle:#"Play" forState:UIControlStateNormal];
[self.playButton addTarget:self action:#selector(playPressed) forControlEvents:UIControlEventTouchUpInside];
// RETURN BUTTON
UIButton *returnButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
returnButton.frame = [[self class] makeCGRectWithCenter:CGPointMake(self.view.frame.size.width/2, 300) width:150 height:50];
[returnButton setTitle:#"Return" forState:UIControlStateNormal];
[returnButton addTarget:self action:#selector(dismissPressed:) forControlEvents:UIControlEventTouchUpInside];
// ACTIVITY
self.activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
self.activityView.frame = [[self class] makeCGRectWithCenter:CGPointMake(self.view.frame.size.width/2, 50) width:100 height:100];
[self.view addSubview:self.recordButton];
[self.view addSubview:self.playButton];
[self.view addSubview:returnButton];
[self.view addSubview:self.activityView];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(#"View did load");
filePath = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:#"temp2.caf"]];
// Setup AudioSession
AVAudioSession *avSession = [AVAudioSession sharedInstance];
[avSession setCategory:AVAudioSessionCategoryPlayAndRecord error:NULL];
[avSession setActive:YES error: NULL];
self.playButton.hidden = YES;
}
#pragma mark - Button Actions
- (void)dismissPressed:(id)sender
{
if ([sender isKindOfClass:[UIButton class]]) {
NSLog(#"Button class dismissed self");
}
else {
NSLog(#"Sender is:%#", [sender class]);
}
[self dismissModalViewControllerAnimated:YES];
}
- (void)stopPressed {
NSLog(#"Stop Pressed");
[self.recordButton setTitle:#"Record" forState:UIControlStateNormal];
self.userIsRecording = NO;
self.playButton.hidden = NO;
self.playButton.enabled = YES;
[self.activityView stopAnimating];
//
}
- (void)recordPressed
{
if (self.userIsRecording) {
[self stopPressed];
}
else {
self.userIsRecording = YES;
self.playButton.enabled = NO;
self.playButton.hidden = YES;
[self.recordButton setTitle:#"Stop" forState:UIControlStateNormal];
[self.activityView startAnimating];
NSDictionary *recorderSettings =
[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
[NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16], AVEncoderBitRateKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithFloat:8000.0], AVSampleRateKey,
[NSNumber numberWithInt:8], AVLinearPCMBitDepthKey, nil];
// Clean temp file
NSFileManager * fm = [NSFileManager defaultManager];
[fm removeItemAtPath:[self.filePath path] error:NULL];
// Record
NSError *error = [NSError alloc];
self.recorder = [[AVAudioRecorder alloc] initWithURL:self.filePath settings:recorderSettings error:&error];
[recorder setDelegate:self];
[recorder prepareToRecord];
if (![recorder record]) {
NSLog(#"Recorder FAIL %#", error );
}
else {
NSLog(#"Recording at %#", [self.filePath absoluteString]);
}
}
}
- (void)playPressed
{
NSFileManager * fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:[self.filePath path]]) {
NSLog(#"File exists at:%#", [self.filePath path]);
NSDictionary *attr = [fm attributesOfItemAtPath:[self.filePath path] error:NULL];
NSLog(#"File attrs:%#", [attr description]);
}
else {
NSLog(#"ERROR: No file exists at:%#", [self.filePath path]);
}
NSError *error = [[NSError alloc] init];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:[[NSData alloc] initWithContentsOfURL:self.filePath] error: &error];
[player setDelegate:self];
if (error) {
NSLog(#"Player initialization Error: %#", error);
}
if (!player) {
NSLog(#"Player is null!");
}
[player prepareToPlay];
if (![player play]) {
NSLog(#"Play Error: %#", error);
}
}
#pragma mark - Lifecycle
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
NSLog(#"View did unload");
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
[player prepareToPlay];
if (![player play]) {
NSLog(#"Play Error: %#", error);
}
You play the file right after you "prepare to play". The buffer maybe it's not still ready at that moment. Make this test. Declare AVAudioPlayer *player as global. Remove if (![player play])... from - (void)playPressed. Now create a new method that will be invoked on other button press. Press your play button, wait a couple of seconds, and press the other button.

Resources