iOS   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何在本地录制后保存音频文件或在目标c中录制firebase?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的应用程序中使用录音功能,但不知道在哪里保存此文件以及在哪里可以看到此文件?还告诉我如何在Firebase存储中存储此文件
我在我的应用中使用Firebase存储.
这是我的代码.

UploadRecordedAudio.h中使用的代码

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@import FirebaseStorage;
@import FirebaseAuth;

@interface UploadRecordedAudio : UIViewController<AVAudioRecorderDelegate,AVAudioPlayerDelegate>
- (IBACtion)btnRecord:(id)sender;
@property (weak,nonatomiC) IBOutlet UIButton *record;
@property (weak,nonatomiC) IBOutlet UIButton *stop;
- (IBACtion)btnStop:(id)sender;

@property (weak,nonatomiC) IBOutlet UIButton *play;
- (IBACtion)btnPlay:(id)sender;

@property (strong,nonatomiC) FIRStorage *storage;
@property (strong,nonatomiC) FIRStorageReference *storageRef;

@end

代码用于UploadRecordedAudio.m:

- (void)viewDidLoad {
    [super viewDidLoad];

    // Disable Stop/Play button when application launches
    [_play setEnabled:NO];
    [_stop setEnabled:NO];

    NSArray *pathComponents = [NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject],@"MyAu@L_381_5@memo.m4a",nil];

    NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
    //NSLog(@"HERE: %@",pathComponents);
    //Setup Audio Session
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    //Define the Recorder SetTings...
    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];

    //Initiate and Prepare the Recorder
    recorder = [[AVAudioRecorder alloc]initWithURL:outputFileURL setTings:recordSetTing error:NULL];
    recorder.delegate = self;
    recorder.meteringEnabled = YES;
    [recorder prepareToRecord];

    NSData *aData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPathComponents:pathComponents]];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,YES);
    NSString *documentsDirectory = [paths objectATindex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory StringByAppendingPathComponent:@"/MyFolder"];
    NSLog(@"%@",dataPath);
    [aData writeToFile:dataPath atomically:YES];
}

- (IBACtion)btnRecord:(id)sender
{
    //Stop the audio player before Recording...
    if (player.playing)
    {
        [player stop];
    }
    if (!recorder.recording)
    {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];

        //Start Recording
        [recorder record];
        [_record settitle:@"Pause Recording" forState:UIControlStateNormal];
    }
    else
    {
        [recorder pause];
        [_record settitle:@"Resume Recording" forState:UIControlStateNormal];
    }
    [_stop setEnabled:YES];
    [_play setEnabled:NO];
}
- (IBACtion)btnPlay:(id)sender
{
    if (!recorder.recording){
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
        [player setDelegate:self];
        [player play];
    }
}

- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag
{
    [_stop setEnabled:NO];
    [_play setEnabled:YES];
}

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    UIAlertController *alert = [UIAlertController alertControllerWithtitle:@"Done" message:@"Finish playing the recording!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithtitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

- (IBACtion)btnStop:(id)sender
{
    [recorder stop];
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:NO error:nil];
}

@end

Please Help me to solve this??? Thanks in advance.

解决方法

您可以在这样的方法中将文件存储在您的设备上

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

并像这样使用它

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


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



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

像这样将音频文件转换为NSData

NSData *audioData = [[NSData alloc] initWithContentsOfFile:filePath];

并像这样上传到firebase

// Obj-C
  NSData *data = ... 
  FIRStorageUploadTask *uploadTask = [riversRef putData:data Metadata:nil 
  completion:^(FIRStorageMetadata *Metadata,NSError *error) {
  if (error != nil) {
// Uh-oh,an error occurred!
   } else {
 // Succeed
   }
   }];

从firebase下载文件

// Create a reference to the file you want to download
  FIRStorageReference *islandRef = [storageRef child:@"images/island.jpg"];

 // Create local filesystem URL
 NSURL *localURL = [NSURL URLWithString:@"path/to/image"];

 // Download to the local filesystem
 FIRStorageDownloadTask *downloadTask = [islandRef writeToFile:localURL 
 completion:^(NSURL *URL,NSError *error){
 if (error != nil) {
    // Uh-oh,an error occurred!
 } else {
     // Local file URL for "images/island.jpg" is returned
  }
 }];

链接如何在obj C中的firebase上创建存储

更新:日期字符串方法

and added a new dateString method to ViewController.m:

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

Firebase storage

大佬总结

以上是大佬教程为你收集整理的ios – 如何在本地录制后保存音频文件或在目标c中录制firebase?全部内容,希望文章能够帮你解决ios – 如何在本地录制后保存音频文件或在目标c中录制firebase?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。