录制音频文件并在iPhone上本地保存 [英] Record audio file and save locally on iPhone

查看:119
本文介绍了录制音频文件并在iPhone上本地保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been looking all over the place for an answer to this but cant find exactly what I need. Basically in my app I am recording voice to an audio file (like the iOS Voice Memo app) and then would like to save it to the local document dir. From some reason the URL that I am being given with the recorded file expires next time I launch the app. Besides, even if it did not, if I record twice, the second file URL gets the same URL as the first one, so I am losing the first file.

录制这样:

    [audioRecorder record];

其中:AVAudioRecorder * audioRecorder;

Where: AVAudioRecorder *audioRecorder;

打得好:

        [audioPlayer play];

其中:AVAudioPlayer * audioPlayer;

Where: AVAudioPlayer *audioPlayer;

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

What is the best way to record voice memo and save it to the local disk on the 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,不知道为什么。

With the data being the data of my AVAudioPlayer NSData property, but BOOL gets 0, and no idea why.

推荐答案

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

Objective-c

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"
}

设置音频会话

Objective-c

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

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

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()
}

stopRecording

Objective-c

Objective-c

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

Swift 4

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

continueRecording

Objective-c

Objective-c

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

}

Swift 4

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

pauseRecording

Objective-c

Objective-c

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

 }

Swift 4

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

这篇关于录制音频文件并在iPhone上本地保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆