简体   繁体   English

AVAudioRecorder不保存录音

[英]AVAudioRecorder not saving recording

I am making an iOS game. 我正在制作一个iOS游戏。 One of the things I need to do is to allow the user to make a quick little audio recording. 我需要做的一件事是允许用户进行快速的小录音。 This all works, but the recording is only temporarily saved. 所有这些都可以,但是录音只是临时保存。 So when the user closes the app and reopens it, the recording should be able to play again, but it doesn't, it gets deleted when I close the app. 因此,当用户关闭应用程序并重新打开它时,录音应该可以再次播放,但不能播放,当我关闭应用程序时,该记录将被删除。 I don't understand what I am doing wrong. 我不明白我在做什么错。 Below is my code: 下面是我的代码:

I setup the AVAudioRecorder in the ViewDidLoad method like this: 我在ViewDidLoad方法中设置AVAudioRecorder ,如下所示:

// Setup audio recorder to save file.
NSArray *pathComponents = [NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], @"MyAudioMemo.m4a", nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];

// Setup audio session.
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];

audio_recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
audio_recorder.delegate = self;
audio_recorder.meteringEnabled = YES;
[audio_recorder prepareToRecord];

I have got the AVAudio delegate methods, too: 我也有AVAudio委托方法:

-(void)audio_playerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    NSLog(@"Did finish playing: %d", flag);
}

-(void)audio_playerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    NSLog(@"Decode Error occurred");
}

-(void)audio_recorderDidFinishRecording:(AVAudioPlayer *)recorder successfully:(BOOL)flag {
    NSLog(@"Did finish recording: %d", flag);
}

-(void)audio_recorderEncodeErrorDidOccur:(AVAudioPlayer *)recorder error:(NSError *)error {
    NSLog(@"Encode Error occurred");
}

When I want to play, record or stop the audio, I have made the following IBActions which are linked to UIButtons: 当我想播放,录制或停止音频时,我做了以下与UIButtons链接的IBAction:

-(IBAction)play_audio {

    NSLog(@"Play");

    if (!audio_recorder.recording){
        audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL:audio_recorder.url error:nil];
        [audio_player setDelegate:self];
        [audio_player play];
    }
}

-(IBAction)record_voice {

    NSLog(@"Record");

    if (!audio_recorder.recording) {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];

        // Start recording.
        [audio_recorder record];
    }

    else {
        // Pause recording.
        [audio_recorder pause];
    }
}

-(IBAction)stop_audio {

    NSLog(@"Stop");

    [audio_recorder stop];

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:NO error:nil];
}

If you try my code you will see that it works, but it only seems to save the audio file temporarily. 如果您尝试使用我的代码,将会看到它的工作原理,但似乎只是暂时保存了音频文件。

What am I doing wrong? 我究竟做错了什么? I thought I had used all the correct AVAudioRecorder methods? 我以为我使用了所有正确的AVAudioRecorder方法?

To make a working recorder and save the recorded files, you need to: 要使记录器正常工作并保存记录的文件,您需要:

  1. Create a new audio session 创建一个新的音频会话
  2. Make sure microphone is connected/working 确保麦克风已连接/正在工作
  3. Start recording 开始录音
  4. Stop recording 停止录音
  5. Save the recorded audio file 保存录制的音频文件
  6. Play the saved voice file 播放保存的语音文件

You're missing step 5 in your code, so the file that's just recorded is still available for you to play, but once you close the app, as it's not saved into an actual file somewhere in the app's directories, you lose it. 您缺少代码中的第5步,因此刚刚录制的文件仍然可供您播放,但是一旦关闭该应用程序,因为它没有保存到应用程序目录中某个位置的实际文件中,便会丢失该文件。 You should add a method to save the recorded audio into a file so that you can access it any time later: 您应该添加一种方法将录制的音频保存到文件中,以便以后可以随时访问它:

-(void) saveAudioFileNamed:(NSString *)filename {

destinationString = [[self documentsPath] stringByAppendingPathComponent:filename];
NSLog(@"%@", destinationString);
NSURL *destinationURL = [NSURL fileURLWithPath: destinationString];

NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
                          [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                          [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
                          [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                          nil];

NSError *error;

audio_recorder = [[AVAudioRecorder alloc] initWithURL:destinationURL settings:settings error:&error];
audio_recorder.delegate = self;
}

Unrelated to this problem, but a general thing to mention is that you must follow Apple's (Objective-C's) naming conventions when defining variables, etc. audio_recording in no way follows these guidelines. 与此问题无关,但要提一提的一般情况是,在定义变量等时,必须遵循Apple(Objective-C)的命名约定audio_recording绝不遵循这些准则。 You could use something like audioRecording instead. 您可以改用audioRecording类的audioRecording

Ok so thanks for @Neeku so much for answering my question, certainly something to take into account but its still not solving the problem. 好的,非常感谢@Neeku回答了我的问题,当然要考虑一些问题,但仍然不能解决问题。 I was searching around and I found this example which works perfectly and more to the point shows me that I was approaching this entire functionality the wrong way. 我在四处搜寻,发现这个例子运行得很好,更重要的是,这向我表明我以错误的方式使用了整个功能。 I think another one of my problems is that my app would delete the previously saved audio file in the ViewDidload method. 我认为我的另一个问题是我的应用程序将删除ViewDidload方法中以前保存的音频文件。 And as well as that I don't think I have used the AVAudioSession instances correctly. 而且,我认为我没有正确使用AVAudioSession实例。

Anyway the example I found is very useful and solves my problem perfectly, you can find it here: Record audio and save permanently in iOS 无论如何,我发现的示例非常有用并且可以完美地解决我的问题,您可以在这里找到它: 录制音频并永久保存在iOS中

Hope that helps anyone else who is having a similar problem to me. 希望对其他与我有类似问题的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM