code doesnt work for different iPhone OS

Discussion in 'iOS Programming' started by newlearner, Oct 21, 2010.

  1. newlearner macrumors member


    Jul 30, 2009

    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.

    - (void)viewDidLoad {
    	NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Audio.mp3", [[NSBundle mainBundle] resourcePath]]];
    	NSError *error;
    	audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    	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,
    	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];	
    	[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
    [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?

  2. ulbador macrumors 68000


    Feb 11, 2010
    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.

Share This Page