How to record and play sound in iPhone app?

10,050

Solution 1

This code should be useful for you:

#import <AudioToolbox/AudioServices.h>

    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;                
    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,          
                                 sizeof (audioRouteOverride),&audioRouteOverride);  

It will increase volume. The functionality of the code is to convert the ordinary sound to speaker sound on ur iPhone. That's why kAudioSessionOverrideAudioRoute_Speaker is used.

Solution 2

Since iOS7 you can fix this issue directly with AVAudioSession

The overrideOutputAudioPort method does the same than AudioSessionSetProperty

NSError *setOverrideError;
NSError *setCategoryError;

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];

if(setCategoryError){
    NSLog(@"%@", [setCategoryError description]);
}

[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&setOverrideError];


if(setOverrideError){
    NSLog(@"%@", [setOverrideError description]);
}

Solution 3

Swift version :

 import AVFoundation
 var overrideError : NSError?
    if AVAudioSession.sharedInstance().overrideOutputAudioPort(.Speaker, error: &error){

    }else{
        print("error in overrideOutputAudioPort " + overrideError!.localizedDescription)
    }

Swift 2:

        do {
        try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
        } catch {
        }

Solution 4

The following code fixed this issue for me:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error: nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
UInt32 doChangeDefault = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefault), &doChangeDefault);
Share:
10,050
Parth Bhatt
Author by

Parth Bhatt

I am iPhone and iPad developer. https://github.com/akashraje/BidirectionalCollectionViewLayout ^[-_,A-Za-z0-9]$ NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:@"(#[a-zA-Z0-9_-]+)" options:NSRegularExpressionCaseInsensitive error:nil]; NSString *stringData = @"This is Parth known as #parth and this is an awesome place. I am fan of #scganguly."; int count = [reg numberOfMatchesInString:stringData options:0 range:NSMakeRange(0, [stringData length])]; NSLog(@"%d",count); if(count&gt;0) { NSArray *array = [reg matchesInString:stringData options:0 range:NSMakeRange(0, [stringData length])]; NSLog(@"%@",array); NSMutableArray *stringArray = [[NSMutableArray alloc] init]; for (NSTextCheckingResult *result in array) { NSString *stringFinal = [stringData substringWithRange:result.range]; if(stringFinal != nil) { [stringArray addObject:stringFinal]; } } NSLog(@"stringArray: %@",stringArray); } For @user: @"(@[a-zA-Z0-9_]+)" NSLog(@"Request String: %@", requestString); NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]]; // NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"url" ofType:@"plist" ]; // NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc]; // NSString *urlLoc = [fileContents objectForKey:@"baseURL"]; NSString *urlLoc = @"http://portal.abc.com/candidate/post-info"; NSLog(@"URL is %@",urlLoc); NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]]; NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]]; [request setHTTPMethod: @"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody: requestData]; http://blog.stackoverflow.com/archive/ https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/CocoaTouch64BitGuide/Introduction/Introduction.html http://nscookbook.com/2013/03/ios-programming-recipe-19-using-core-motion-to-access-gyro-and-accelerometer/ http://code4app.net/category/coremotion http://www.devx.com/wireless/Article/44799 upload audio file to php ios Android post request on IOS https://developers.facebook.com/docs/ios/share https://github.com/oliverbarreto/FastFavs/blob/master/TODO2.h

Updated on June 11, 2022

Comments

  • Parth Bhatt
    Parth Bhatt almost 2 years

    I tried using AVAudioSession and AVAudioPlayer to record and play sounds respectively but the sound volume is very low.

    I tried putting volume value of AVAudioPlayer to 1.0 and more but didn't help much.

    What could be my other options to record sound which can be loud enough to play back?

  • Parth Bhatt
    Parth Bhatt about 13 years
    Thanks for the input. I will check it out and get back to you soon :)
  • Parth Bhatt
    Parth Bhatt about 13 years
    Thanks a lot this did work :) I was in search of a solution to this since a day now.
  • manuelBetancurt
    manuelBetancurt over 12 years
    Don't forget the import statement. Perhaps obvious for the more experienced programmers... #import <AudioToolbox/AudioServices.h>
  • SinisterMJ
    SinisterMJ over 12 years
    I added that to the answer above, thanks for mentioning the import required.
  • Olie
    Olie over 10 years
    I got it to work (the sounds comes out of the speakers), but I'm not sure if I'm using it correctly. Is this a one-time thing at app-launch? Once at viewDidLoad for my controller? Once every time I make a new AVAudioPlayer? As KKendal asked: where does this go? Thanks!
  • Martin Christmann
    Martin Christmann over 10 years
    Your code works just fine :) but it is now deprecated since iOS7. Please see my answer below for an updated solution.
  • blwinters
    blwinters over 8 years
    With Swift 2, this is now a do-try-catch situation, no need for overrideError optional
  • Fadi Abuzant
    Fadi Abuzant over 6 years
    this line saved my life, thanks man [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&setOverrideError];