iphone - 录制音频文件并保存在 iPhone 本地

标签 iphone objective-c ios xcode

我一直在到处寻找这个问题的答案,但找不到我需要的东西。基本上在我的应用程序中,我将语音录制到音频文件(如 iOS 语音备忘录应用程序),然后想将其保存到本地文档目录。由于某种原因,在我下次启动该应用程序时,为我提供的录制文件的 URL 会过期。此外,即使没有,如果我录制两次,第二个文件的 URL 与第一个文件的 URL 相同,所以我丢失了第一个文件。

这样记录:

    [audioRecorder record];

其中:AVAudioRecorder *audioRecorder;

播放正常:

        [audioPlayer play];

其中:AVAudioPlayer *audioPlayer;

在 iPhone 上录制语音备忘录并将其保存到本地磁盘的最佳方法是什么?

谢谢。

更新:

我尝试使用这段代码:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
BOOL status = [data writeToFile:filePath atomically:YES];

数据是我的 AVAudioPlayer NSData 属性的数据,但 BOOL 得到 0,不知道为什么。

最佳答案

返回我们用作声音文件名的当前日期和时间。

objective-c

- (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"];
}

swift 4

func dateString() -> String {
  let formatter = DateFormatter()
  formatter.dateFormat = "ddMMMYY_hhmmssa"
  let fileName = formatter.string(from: Date())
  return "\(fileName).aif"
}

设置 Audio Session

objective-c

- (BOOL) startAudioSession
{
// Prepare the audio session
NSError *error;
AVAudioSession *session = [AVAudioSession sharedInstance];

if (![session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error])
{
    NSLog(@"Error setting session category: %@", error.localizedFailureReason);
    return NO;
}


if (![session setActive:YES error:&error])
{
    NSLog(@"Error activating audio session: %@", error.localizedFailureReason);
    return NO;
}

return session.inputIsAvailable;
}

swift 4

func startAudioSession() -> Bool {

 let session = AVAudioSession()
 do {
  try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
 } catch(let error) {
  print("--> \(error.localizedDescription)")
}
 do {
   try session.setActive(true)
 } catch (let error) {
   print("--> \(error.localizedDescription)")
 }
   return session.isInputAvailable;
}

录制声音..

objective-c

- (BOOL) 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];

// Create recorder
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
if (!recorder)
{
    NSLog(@"Error establishing recorder: %@", error.localizedFailureReason);
    return NO;
}

// Initialize degate, metering, etc.
recorder.delegate = self;
recorder.meteringEnabled = YES;
//self.title = @"0:00";

if (![recorder prepareToRecord])
{
    NSLog(@"Error: Prepare to record failed");
    //[self say:@"Error while preparing recording"];
    return NO;
}

if (![recorder record])
{
    NSLog(@"Error: Record failed");
//  [self say:@"Error while attempting to record audio"];
    return NO;
}

// Set a timer to monitor levels, current time
timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(updateMeters) userInfo:nil repeats:YES];

return YES;
}

swift 4

func record() -> Bool {

    var settings: [String: Any]  = [String: String]()
    settings[AVFormatIDKey] = kAudioFormatLinearPCM
    settings[AVSampleRateKey] = 8000.0
    settings[AVNumberOfChannelsKey] = 1
    settings[AVLinearPCMBitDepthKey] = 16
    settings[AVLinearPCMIsBigEndianKey] = false
    settings[AVLinearPCMIsFloatKey] = false
    settings[AVAudioQualityMax] = AVEncoderAudioQualityKey

    let searchPaths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true)
    let documentPath_ = searchPaths.first
    let pathToSave = "\(documentPath_)/\(dateString)"
    let url: URL = URL(pathToSave)

    recorder = try? AVAudioRecorder(url: url, settings: settings)

    // Initialize degate, metering, etc.
    recorder.delegate = self;
    recorder.meteringEnabled = true;
    recorder?.prepareToRecord()
    if let recordIs = recorder {
        return recordIs.record()
    }
    return false
    }

播放声音...从文档目录中检索

objective-c

-(void)play
{

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

 NSFileManager *fileManager = [NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:[self recordingFolder]]) 
    { 

    arrayListOfRecordSound=[[NSMutableArray alloc]initWithArray:[fileManager  contentsOfDirectoryAtPath:documentPath_ error:nil]];

    NSLog(@"====%@",arrayListOfRecordSound);

}

   NSString  *selectedSound =  [documentPath_ stringByAppendingPathComponent:[arrayListOfRecordSound objectAtIndex:0]];

    NSURL   *url =[NSURL fileURLWithPath:selectedSound];

     //Start playback
   player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

   if (!player)
   {
     NSLog(@"Error establishing player for %@: %@", recorder.url, error.localizedFailureReason);
     return;
    }

    player.delegate = self;

    // Change audio session for playback
    if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error])
    {
        NSLog(@"Error updating audio session: %@", error.localizedFailureReason);
        return;
    }

    self.title = @"Playing back recording...";

    [player prepareToPlay];
    [player play];


}

swift 4

func play() {
        let searchPaths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true)
    let documentPath_ = searchPaths.first
      let fileManager = FileManager.default
        let arrayListOfRecordSound: [String]
        if fileManager.fileExists(atPath: recordingFolder()) {
    let arrayListOfRecordSound = try? fileManager.contentsOfDirectory(atPath: documentPath_)
    }

let selectedSound = "\(documentPath_)/\(arrayListOfRecordSound.first)"
let url = URL.init(fileURLWithPath: selectedSound)
let player = try? AVAudioPlayer(contentsOf: url)
player?.delegate = self;
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
player?.prepareToPlay()
player?.play()
}

停止录制

objective-c

- (void) stopRecording
{
// This causes the didFinishRecording delegate method to fire
  [recorder stop];
}

swift 4

func stopRecording() {
 recorder?.stop()
}

继续录制

objective-c

- (void) continueRecording
{
// resume from a paused recording
[recorder record];

}

swift 4

func continueRecording() {
 recorder?.record()
}

暂停录音

objective-c

 - (void) pauseRecording
 {  // pause an ongoing recording
[recorder pause];

 }

swift 4

func pauseRecording() {
 recorder?.pause()
}

关于iphone - 录制音频文件并保存在 iPhone 本地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135687/

相关文章:

如果连接不可用,iOS 服务请求的重试机制

iphone - 有没有办法简化这个 IBOutletConnection 语句?

ios - iBeacon:CBPeripheralManager: 0x1557b230 只能在开机状态下接受这个命令

iphone - 如何从 NSMutableArray 访问 NSObject 类变量进行排序

ios取消NSURLConnection Swift

ios - CLLocationManager.location 为零

ios - RestKit对象映射问题

iphone - annotationView 覆盖 drawRect,带 alpha 的图像

iphone - 删除以某个单词开头的所有 NSUserDefaults

ios - 如何在 viewDidAppear 中只执行一次?