Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

newlearner

macrumors member
Original poster
Jul 30, 2009
37
0
india
Hello,

I want to play an audio when someone speaks in the iPhone's mic. This code works perfectly in iPhone 2G(OS 3.1.3), but when it is tested in iPhone 4, it doesnt work. I checked for API and method differences, but could not find any.



Code:
- (void)viewDidLoad {

	NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Audio.mp3", [[NSBundle mainBundle] resourcePath]]];
	
	NSError *error;
	audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
	audioPlayer.delegate=self;
	if (audioPlayer == nil)
		NSLog(@" %@ ", [error description]);

	audioSession = [[AVAudioSession sharedInstance] retain];
	[audioSession setActive:YES error: nil];

	
    [super viewDidLoad];
}


-(IBAction) micAction{

	[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: nil];
	NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
	
	NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
							  [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
							  [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
							  [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
							  [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
							  nil];
	
	NSError *error;
	
	recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
	
	if (recorder) {
		[recorder prepareToRecord];
		recorder.meteringEnabled = YES;
		[recorder record];
		levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.03 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: NO];
	}
}

- (void)levelTimerCallback:(NSTimer *)t {
	[recorder updateMeters];
	if([recorder averagePowerForChannel:0]>-38){
		if ([audioPlayer prepareToPlay]) {
			[recorder stop];
			[recorder release];
			[levelTimer invalidate];
			[self playSound];	
		}
	}	
}

-(void)playSound{
	[audioSession setCategory:AVAudioSessionCategoryPlayback error: nil];
	if ([audioPlayer prepareToPlay])
		[audioPlayer play];	
		
}

To make sure that the audio is playing in iPhone 4, i'd also set up an IBAction event, which is working fine. Also, for testing I'd set up a label to display the value of
Code:
[recorder averagePowerForChannel:0]
after the button is pressed. This label updates itself as per the timer in 2G, but in iPhone 4 it displays just one value on the click event.

Can you please point out what the error is?

Thanks
 
Are you sure it didn't give you deprecation warnings?

Otherwise, you are suppressing the errors all over the place with the error:nil part. Don't suppress them and do something with an NSError object so you can see what is going on.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.