xcode 录制音频并永久保存在 iOS 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15059089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:50:53  来源:igfitidea点击:

Record audio and save permanently in iOS

iosobjective-cxcoderecord

提问by es1

I have made 2 iPhone apps which can record audio and save it to a file and play it back again.

我制作了 2 个 iPhone 应用程序,它们可以录制音频并将其保存到文件中并再次播放。

One of them uses AVAudiorecorder and AVAudioplayer. The second one is Apple's SpeakHereexample with Audio Queues.

其中之一使用 AVAudiorecorder 和 AVAudioplayer。第二个是 Apple 的带有音频队列的SpeakHere示例。

Both run on Simulater as well as the Device.

两者都在模拟器和设备上运行。

BUT when I restart either app the recorded file is not found!!! I've tried all possible suggestions found on stackoverflow but it still doesnt work!

但是当我重新启动任一应用程序时,都找不到录制的文件!!!我已经尝试了在 stackoverflow 上找到的所有可能的建议,但它仍然不起作用!

This is what I use to save the file:

这是我用来保存文件的内容:

NSArray *dirPaths; 
NSString *docsDir; 

dirPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); 
docsDir = [dirPaths objectAtIndex:0]; 

NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"sound1.caf"]; 
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

回答by es1

Ok I finally solved it. The problem was that I was setting up the AVAudioRecorder and file the path in the viewLoad of my ViewController.m overwriting existing files with the same name.

好的,我终于解决了。问题是我正在设置 AVAudioRecorder 并在我的 ViewController.m 的 viewLoad 中写入路径,覆盖具有相同名称的现有文件。

  1. After recording and saving the audio to file and stopping the app, I could find the file in Finder. (/Users/xxxxx/Library/Application Support/iPhone Simulator/6.0/Applications/0F107E80-27E3-4F7C-AB07-9465B575EDAB/Documents/sound1.caf)
  2. When I restarted the application the setup code for the recorder (from viewLoad) would just overwrite my old file called:

    sound1.caf

  3. with a new one. Same name but no content.

  4. The play back would just play an empty new file. --> No Sound obviously.

  1. 录制音频并将其保存到文件并停止应用程序后,我可以在 Finder 中找到该文件。(/Users/xxxxx/Library/Application Support/iPhone Simulator/6.0/Applications/0F107E80-27E3-4F7C-AB07-9465B575EDAB/Documents/sound1.caf)
  2. 当我重新启动应用程序时,记录器的设置代码(来自 viewLoad)只会覆盖我的旧文件:

    sound1.caf

  3. 用一个新的。同名但无内容。

  4. 回放只会播放一个空的新文件。--> 显然没有声音。



So here is what I did:

所以这就是我所做的:

I used NSUserdefaults to save the path of the recorded file name to be retrieved later in my playBack method.

我使用 NSUserdefaults 来保存录制文件名的路径,以便稍后在我的 playBack 方法中检索。



cleaned viewLoad in ViewController.m :

清除 ViewController.m 中的 viewLoad :

- (void)viewDidLoad
{

     AVAudioSession *audioSession = [AVAudioSession sharedInstance];

     [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

     [audioSession setActive:YES error:nil];

     [recorder setDelegate:self];

     [super viewDidLoad];
}

edited record in ViewController.m :

在 ViewController.m 中编辑记录:

- (IBAction) record
{

    NSError *error;

    // Recording settings
    NSMutableDictionary *settings = [NSMutableDictionary dictionary];

    [settings setValue: [NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    [settings setValue: [NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];
    [settings setValue: [NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
    [settings setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
    [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
    [settings setValue:  [NSNumber numberWithInt: AVAudioQualityMax] forKey:AVEncoderAudioQualityKey];

    NSArray *searchPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath_ = [searchPaths objectAtIndex: 0];

    NSString *pathToSave = [documentPath_ stringByAppendingPathComponent:[self dateString]];

    // File URL
    NSURL *url = [NSURL fileURLWithPath:pathToSave];//FILEPATH];


    //Save recording path to preferences
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];


    [prefs setURL:url forKey:@"Test1"];
    [prefs synchronize];


    // Create recorder
    recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];

    [recorder prepareToRecord];

    [recorder record];
}

edited playback in ViewController.m:

在 ViewController.m 中编辑播放:

-(IBAction)playBack
{

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

[audioSession setActive:YES error:nil];


//Load recording path from preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];


temporaryRecFile = [prefs URLForKey:@"Test1"];



player = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];



player.delegate = self;


[player setNumberOfLoops:0];
player.volume = 1;


[player prepareToPlay];

[player play];


}

and added a new dateString method to ViewController.m:

并向 ViewController.m 添加了一个新的 dateString 方法:

- (NSString *) dateString
{
    // return a formatted string for a file name
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"ddMMMYY_hhmmssa";
    return [[formatter stringFromDate:[NSDate date]] stringByAppendingString:@".aif"];
}


Now it can load the last recorded file via NSUserdefaults loading it with:

现在它可以通过 NSUserdefaults 加载最后记录的文件:

    //Load recording path from preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];


temporaryRecFile = [prefs URLForKey:@"Test1"];



player = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];

in (IBAction)playBack. temporaryRecFile is a NSURL variable in my ViewController class.

在(IBAction)播放中。tempRecFile 是我的 ViewController 类中的 NSURL 变量。

declared as following ViewController.h :

声明如下 ViewController.h :

@interface SoundRecViewController : UIViewController <AVAudioSessionDelegate,AVAudioRecorderDelegate, AVAudioPlayerDelegate>
{
......
......
    NSURL *temporaryRecFile;

    AVAudioRecorder *recorder;
    AVAudioPlayer *player;

}
......
......
@end