【问题标题】:How to record voice in .m4a format如何以 .m4a 格式录制语音
【发布时间】:2011-05-15 19:48:14
【问题描述】:

我已经创建了一个 iPhone 应用程序来录制。它将记录在 .caf 文件中。

但我想以 .m4a 格式录制。

请帮我做这件事。

谢谢。

【问题讨论】:

    标签: iphone avaudiorecorder m4a


    【解决方案1】:

    这是用于录制 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
        }
    

    【讨论】:

    • 您将录音保存为什么格式? .caf? .m4a?你的 sn-p 不清楚。
    • @Josh sn-p 以 m4a 格式保存,该格式设置在 2 个位置:1)在“recordSettings”kAudioFormatMPEG4AAC 参数中和 2)作为来自自身的显式 .m4a 扩展名。目录 URL()。我已将 directoryURL() 的代码添加到答案中,以便您查看它的来源。重要提示:由于某种原因,大多数 AVSampleRateKey 和 AVFormatIDKey 录制设置的组合实际上会崩溃,因此您将仅限于那些有效的组合(我通过反复试验发现)
    【解决方案2】:

    这是一个替代代码示例,它将文件编码为 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'的文件就可以使用了。

    【讨论】:

    • 您可能需要等待audioRecorderDidFinishRecording:successfully: 才能知道文件是否有效。
    • 太好了,这非常适合直接录制到 *m4a,而无需稍后转换。您应该使用 AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation 而不是 AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation,因为它自 4.0 以来已被弃用(仍然有效,但以防万一)。
    • 有人有我可以运行的示例应用程序来查看此代码的运行情况吗?我打算将它插入 iOS 开发中心文档中的示例 Recorder 应用程序,但对我来说有点复杂。谢谢!
    猜你喜欢
    • 2014-02-13
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多