How to record and play sound in iPhone app?
I tried using AVAudioSession
and AVAudioPlayer
to record and play sounds respectively but the sound volume is very low.
I tried putti开发者_Python百科ng 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?
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.
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]);
}
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 {
}
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);
MAN, try this.
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
if (![session setCategory:AVAudioSessionCategoryPlayback
withOptions:kAudioSessionOverrideAudioRoute_Speaker
error:&setCategoryError]) {
// handle error
}
NSError *error;
NSData * data = [NSData dataWithContentsOfURL:self.playlet.urlSound];
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:data fileTypeHint:@"aac" error:&error];
self.audioPlayer.delegate = self;
if (error)
NSLog(@"Error: %@",
[error localizedDescription]);
else
[_audioPlayer play];
just set this [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&setOverrideError]; It works for me.
精彩评论