我已经创建了一个 iPhone 应用程序来录制。它将记录在 .caf 文件中。
但我想以 .m4a 格式录制。
请帮助我做到这一点。
谢谢。
这是一个替代代码示例,它将文件编码为 m4a 中的 AAC:
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSURL *tmpFileUrl = [NSURL fileURLWithPath:[docsDir stringByAppendingPathComponent:@"tmp.m4a"]];
NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
[NSNumber numberWithFloat:16000.0], AVSampleRateKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
nil];
NSError *error = nil;
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:tmpFileUrl settings:recordSettings error:&error];
[recorder prepareToRecord];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryRecord error:nil];
[session setActive:YES error:nil];
[recorder record];
然后结束我使用的录音:
[recorder stop];
AVAudioSession *session = [AVAudioSession sharedInstance];
int flags = AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation;
[session setActive:NO withFlags:flags error:nil];
然后'tmpFileUrl'
就可以使用文件了。
这是用于录制 m4a 音频文件的有效 SWIFT 代码。请记住,在 iOS 中找到正确的格式参数来生成可用的音频文件真的很痛苦。经过多次试验和错误,我发现这种组合有效。我希望它可以节省您的时间,享受!
let recordSettings: [String : AnyObject] = [AVSampleRateKey : NSNumber(float: Float(16000)),
AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
AVNumberOfChannelsKey : NSNumber(int: 1),
AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Low.rawValue))]
func initializeAudioSession(){
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioRecorder = AVAudioRecorder(URL: self.directoryURL()!,
settings: recordSettings)
audioRecorder.delegate = self
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord()
} catch let error as NSError{
print("ERROR Initializing the AudioRecorder - "+error.description)
}
}
func recordSpeechM4A(){
if !audioRecorder.recording {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(true)
audioRecorder.record()
print("RECORDING")
} catch {
}
}
}
func directoryURL() -> NSURL { //filename helper method
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
filepath = urls[0]
let documentDirectory = urls[0] as NSURL
print("STORAGE DIR: "+documentDirectory.description)
//print("---filepath: "+(filepath?.description)!)
let soundURL = documentDirectory.URLByAppendingPathComponent("recordedAudio.m4a") //.m4a
print("SAVING FILE: "+soundURL.description)
return soundURL
}