发送 AVAudioRecorder 到服务器 iOS

2024-02-16

在过去的几天里,我试图将本地保存的声音记录上传到服务器(该服务器使用 php 文件处理它并将其保存到服务器)。 问题是我找不到办法做到这一点。

录制声音(AVAudioRecorder)时,它保存在“NSTemporaryDirectory()”中:

NSURL *temporaryRecFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"VoiceFile"]]];

现在,我到处检查答案都是使用ASIHTTP请求 http://allseeing-i.com/ASIHTTPRequest/。 但问题是ios6不支持。

还有一些其他库,但无论我如何尝试,都不起作用。 如果有人可以帮助我,我会很高兴...

这是我的代码:

视图控制器.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>

@interface ViewController : UIViewController <AVAudioRecorderDelegate,AVAudioPlayerDelegate>
{
    UIButton *recordButton;
    UIButton *playButton;
    UIButton *uploadFile;
    UILabel *recStateLabel;
    BOOL isNotRecording;

    NSURL *temporaryRecFile;
    AVAudioRecorder *recorder;
    AVAudioPlayer *player;
}

@property (nonatomic,retain) IBOutlet UIButton *uploadFile;
@property (nonatomic,retain) IBOutlet UIButton *playButton;
@property (nonatomic,retain) IBOutlet UIButton *recordButton;
@property (nonatomic,retain) IBOutlet UILabel *recStateLabel;

-(IBAction)recording;
-(IBAction)playback;
-(IBAction)upload;

@end

视图控制器.m

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "STHTTPRequest.h"

@interface ViewController ()

@end

@implementation ViewController 

@synthesize recordButton,playButton,uploadFile,recStateLabel;

-(IBAction)recording
{
    if(isNotRecording)
    {
        isNotRecording = NO;
        [recordButton setTitle:@"Stop" forState:UIControlStateNormal];
        playButton.hidden = YES;
        recStateLabel.text = @"Recording";

        temporaryRecFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"VoiceFile"]]];

        NSDictionary *recordSettings = [NSDictionary
                                        dictionaryWithObjectsAndKeys:
                                        [NSNumber numberWithInt:AVAudioQualityMin],
                                        AVEncoderAudioQualityKey,
                                        [NSNumber numberWithInt:16],
                                        AVEncoderBitRateKey,
                                        [NSNumber numberWithInt: 2],
                                        AVNumberOfChannelsKey,
                                        [NSNumber numberWithFloat:44100.0],
                                        AVSampleRateKey,
                                        nil];


        recorder = [[AVAudioRecorder alloc]initWithURL:temporaryRecFile settings:recordSettings error:nil];
        [recorder setDelegate:self];
        [recorder prepareToRecord];
        [recorder record];
    }
    else
    {
        isNotRecording = YES;
        [recordButton setTitle:@"Rec" forState:UIControlStateNormal];
        playButton.hidden = NO;
        recStateLabel.text = @"Not Recording";
        [recorder stop];
    }
}

-(IBAction)playback
{
    player = [[AVAudioPlayer alloc]initWithContentsOfURL:temporaryRecFile error:nil];
    //player.volume = 1;
    [player setVolume: 1.0];
    [player play];
}

-(IBAction)upload
{
    NSLog(@"upload");
    recStateLabel.text = @"Uploading";

    NSData *data = [NSData dataWithContentsOfFile:NSTemporaryDirectory()];
    NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@""];
    [urlString appendFormat:@"%@", data];
    NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
                               allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSString *baseurl = @"http://efron.org.il/dev/singsong/upload.php";

    NSURL *url = [NSURL URLWithString:baseurl];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue:@"application/x-www-form-urlencoded"
      forHTTPHeaderField:@"Content-Type"];
    [urlRequest setHTTPBody:postData];

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    [connection start];

    NSLog(@"Started!");

    /*
    STHTTPRequest *r = [STHTTPRequest requestWithURLString:@"http://efron.org.il/dev/singsong/upload.php"];

    r.completionBlock = ^(NSDictionary *headers, NSString *body) {
        // ...
    };

    r.errorBlock = ^(NSError *error) {
        NSLog(@"error");
    };

    [r setFileToUpload:NSTemporaryDirectory() parameterName:@"sound"];
    [r startAsynchronous];

    ///..................///

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSMutableData *postData = [NSMutableData data];
    NSString *header = [NSString stringWithFormat:@"--%@\r\n", boundary];
    [postData appendData:[header dataUsingEncoding:NSUTF8StringEncoding]];

    //add your filename entry
    NSString *contentDisposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", @"filename", @"iosaudio"];

    [postData appendData:[contentDisposition dataUsingEncoding:NSUTF8StringEncoding]];

    [postData appendData:[NSData dataWithContentsOfFile:NSTemporaryDirectory()]];
    NSString *endItemBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n",boundary];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"POST"];
    [request setURL:[NSURL URLWithString:@"http://efron.org.il/dev/singsong/upload.php"]];
    [postData appendData:[endItemBoundary dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postData];

    ///...........///

    NSURL *url = [NSURL URLWithString:@"http://efron.org.il/"];
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    NSData *songData = [NSData dataWithContentsOfURL:temporaryRecFile];
    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"dev/singsong/upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFormData:songData name:@"file"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        recStateLabel.text = [NSString stringWithFormat:@"Sent %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite];
    }];

    [httpClient enqueueHTTPRequestOperation:operation];
     */

}

- (void)viewDidLoad
{

    isNotRecording = YES;
    playButton.hidden = YES;
    recStateLabel.text = @"Not Recording";

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession setActive:YES error:nil];


    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

The 视图控制器.m包括我用库进行的一些测试,例如STHTTP请求 https://github.com/nst/STHTTPRequest和 AF 网络


这行代码对我来说很好用

现在我已经发布了我的整个代码录制、保存、播放并发布到服务器

Edited:-

SoundRecordVC.h

///***********************  SoundRecordVC.h   ***************************//

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface SoundRecordVC : UIViewController<AVAudioPlayerDelegate,AVAudioRecorderDelegate>
{

    BOOL stopBtnFlag;
    BOOL pauseBtnFlag;

    NSTimer *timer;

    AVAudioPlayer *audioPlayer;
    AVAudioRecorder *audioRecorder;

}

    // ------------------- Properties ---------------------
@property (weak, nonatomic) IBOutlet UIButton *recordBtn;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;


@property (strong, nonatomic) AVAudioRecorder *audioRecorder;
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

@property (strong,nonatomic) NSString *friendId;


    // ------------------- IBAction -----------------
- (IBAction)recordBtnPressed:(id)sender;
- (IBAction)playBtnPressed:(id)sender;

SoundRecordVC.m

//***********************  SoundRecordVC.m   ***************************//


#import "SoundRecordVC.h"

@interface SoundRecordVC.m ()

@end

@implementation SoundRecordVC.m

@synthesize recordBtn;
@synthesize playBtn;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

#pragma mark -
#pragma mark - methods

- (IBAction)recordBtnPressed:(id)sender
{
    if (!stopBtnFlag)
    {
        if (!audioRecorder.recording)
        {
            [self performSelectorOnMainThread:@selector(setUpAudioRecorder) withObject:nil waitUntilDone:YES];
            [audioRecorder record];
             NSLog(@"Recording...");

        }
        stopBtnFlag = YES;
    }
    else
    {
        [audioRecorder stop];
        stopBtnFlag = NO;

      }
}
-(void)setUpAudioRecorder
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];

    // --------------------- Setting for audio ----------------------//

    NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:AVAudioQualityMedium],AVEncoderAudioQualityKey,[NSNumber numberWithInt:16],AVEncoderBitRateKey,[NSNumber numberWithInt:2],AVNumberOfChannelsKey,[NSNumber numberWithInt:44100.0],AVSampleRateKey, nil];

    NSError *error = nil;


    // --------------------- File save Path ----------------------//
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sounds.caf", documentsDirectory]];


    audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];
    audioRecorder.delegate = self;

    if ([audioRecorder prepareToRecord] == YES){
        [audioRecorder prepareToRecord];

    }else {
        int errorCode = CFSwapInt32HostToBig ([error code]);
        NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);

    }
}

- (IBAction)playBtnPressed:(id)sender {

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

    //----------------------loading files to player for playing------------------------------------//

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sounds.caf", documentsDirectory]];


    NSError *error;
    NSLog(@"url is %@",url);

    [audioPlayer stop];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;
    audioPlayer.delegate=self;
    [audioPlayer prepareToPlay];

    if(!pauseBtnFlag){

        NSLog(@"Playing.......");
        [audioPlayer play];
         pauseBtnFlag=YES;

    }else{
         NSLog(@"Pause");
        [audioPlayer pause];
        pauseBtnFlag=NO;
    }

}

#pragma mark - 
#pragma mark - AVRecorder Delegate

-(void)audioRecorderDidFinishRecording: (AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    NSLog (@"audioRecorderDidFinishRecording:successfully");
    NSLog(@"Stopped");

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

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{

}

-(void)dataUploadOnServer
        {
             NSLog(@"upload");
                recStateLabel.text = @"Uploading";

                NSString *baseurl = @"http://efron.org.il/dev/singsong/upload.php";
                NSURL *dataURL = [NSURL URLWithString:baseurl]; 

                   NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:dataURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

                        [dataRqst setHTTPMethod:@"POST"];

                        NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
                        NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];

                        [dataRqst addValue:headerBoundary forHTTPHeaderField:@"Content-Type"];

                        NSMutableData *postBody = [NSMutableData data];


                        // -------------------- ---- Audio Upload Status ---------------------------\\
                        //pass MediaType file

                        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
                        [postBody appendData:[@"Content-Disposition: form-data; name=\"Data\"; filename=\"myVoice.mp3\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
                        [postBody appendData:[@"Content-Type: audio/caf\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
                        [postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
                        //*******************load locally store audio file********************//
                        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                        NSString *documentsDirectory = [paths objectAtIndex:0];
                        NSString *audioUrl = [NSString stringWithFormat:@"%@/record.mp3", documentsDirectory]; 


                        // get the audio data from main bundle directly into NSData object
                        NSData *audioData;
                        audioData = [[NSData alloc] initWithContentsOfFile:audioUrl];
                        // add it to body
                        [postBody appendData:audioData];
                        [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

                        // final boundary

                        [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

                        // add body to post

                        [dataRqst setHTTPBody:postBody];

                        NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init];
                        NSError* error = [[NSError alloc] init] ;

                        //synchronous filling of data from HTTP POST response
                        NSData *responseData = [NSURLConnection sendSynchronousRequest:dataRqst returningResponse:&response error:&error];

                        //convert data into string
                        NSString *responseString = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];

                        NSLog(@"Response String %@",responseString);
}


#pragma mark -

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload
{
    [self setPlayBtn:nil];
    [super viewDidUnload];
}

@end

我希望它对你有用

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

发送 AVAudioRecorder 到服务器 iOS 的相关文章

随机推荐

  • 如何从AccessibilityNodeInfo获取webview

    我正在创建一个需要使用 AccessibilityService 的应用程序 并且获取其他应用程序的窗口内容也是没有问题的 我已从窗口内容中检测到所有可用的子项 并且该子项显示在 AccessibilityNodeInfo 中 现在我在 A
  • log4net 每次运行一个文件

    我需要我的应用程序在每次运行时创建一个日志文件 我的首选格式是App log yyyy MM dd HH mm ss 如果那不可能 我会满足App log yyyy MM dd counter 这是我当前的附加程序配置
  • 最值得一读的Python模块

    我已经学习Python有一段时间了 我对其特性有了很好的了解 但我想改进我的编码风格 我认为阅读 Python 模块的源代码是个好主意 有谁可以特别推荐一下吗 相关主题 寻找美观且具有指导意义的 Python 代码的初学者 https st
  • 到 Web 服务的 XMLHttpRequest 在 Web Worker 中不起作用

    如果从主 javascript 调用 下面的代码可以完美运行 但它不会在 Web Worker 中运行 function getSpecData detailLvl startWeek endWeek mkt var params deta
  • Xcode 5 升级 - 现在 nsobject.h 存在类“NSObject”的重复接口定义错误

    我昨晚升级到了 X Code 5 现在 当我继续开发我的一个 iOS 应用程序 在以前的 Xcode 版本上编译得很好 时 我遇到了一个似乎无法解决的错误 当我构建应用程序时 出现编译错误 duplicate interface defin
  • iOS 5.x 和 iOS 6 调用 application:didFinishLaunchingWithOptions: 的次数不同

    Subj 在 iOS 5 x 中 我得到了方法调用的下一个结果 UIViewController initWithCoder UIApplicationDelegate didFinishLaunchingWithOptions UIVie
  • 容器适配器不支持迭代器

    在一篇关于 STL 的 C 文章中 有人说 由于容器适配器不支持迭代器 因此它们不能与 STL 算法一起使用 但它没有解释为什么容器适配器不支持迭代器 有人能给我同样的解释吗 具有迭代器的堆栈或队列有什么意义 根据定义 堆栈是只能压入和弹出
  • 使用 ggplot 绘制栅格因子值

    我在使用 ggplot2 绘制具有因子值的栅格时遇到问题 library ggplot2 library raster 首先 加载栅格数据 f lt system file external test grd package raster
  • Dart PetitParser 获取使用 ExpressionBuilder 创建的 AST 数据结构

    我是 petitparser 的新手 但它看起来像是解析器的声波螺丝刀 对于我的第一个项目 我正在构建代码来解析一个简单的表达式 该表达式构建 Node 对象的 AST 树 然后使用一些规则遍历该树以最小化不需要的括号 我不知道要传递什么到
  • 通过浏览器原生 Facebook 登录体验

    我见过这个问题的几种风格 但没有具体的答案 所以我自己尝试一下 我正在尝试通过浏览器在我的基于 Facebook 的应用程序中构建 Facebook 登录体验 这将要求用户尽可能不记住他们的密码 这意味着如果 他们通过桌面浏览器登录并且已经
  • Hibernate子对象不保存

    我有一个员工和员工部门表 一名员工可以拥有多个部门 我已经在 MySQL 中定义了表并使用 JPA 生成了实体 package model import java io Serializable import javax persisten
  • 使用prepareForSegue作为按钮

    您好 我以编程方式创建按钮并将按钮连接到另一个视图 但我遇到了 segue 问题 我应该对故事板使用prepareForSegue方法 但我不知道互联网上有一些示例 但当我使用该示例时我会收到错误 请你帮助我 提前致谢 这是我的代码 创建按
  • Ruby,堆栈级别太深(SystemStackError)

    我有以下代码 class BookPrice attr accessor price def initialize price price price end def price in cents Integer price 100 0 5
  • 如何在 Qt 中设置适用于 Windows 的应用程序版本?

    When my application crashes the Windows Event Viewer always reports my application version as 0 0 0 0 I can t figure how
  • 访问第三方库中的 web.config 文件

    我正在编写一个 IHttpFilter 它需要位于一个单独的项目 这些都是 C 项目 中 以便在一组 ASP NET MVC 应用程序中使用 在 IHttpFilter 中 我必须确定 web config 文件中指定的一些内容 有没有办法
  • jQuery 追加元素(如果不存在),否则替换

    这是一小段代码 var el something find test if el length something append div class test somecontent div else el replaceWith div
  • 从 C 调用 PHP

    我正在尝试编写一个使用 PHP 作为脚本语言的应用程序 该应用程序是一个 CGI 处理程序 我希望能够从中调用 PHP 页面 我正在寻找可以让我在 C 程序中初始化 PHP 的代码 然后向其传递包含 php 代码的缓冲区或文件名 以供其解析
  • 数据库选项:为什么默认情况下“SET ANSI_NULLS OFF”对于新数据库是关闭的?

    使用 SSMS 2014 当我使用 SSMS 创建新数据库时 新数据库的默认设置有一些奇怪的地方 ALTER DATABASE del SET ANSI NULL DEFAULT OFF GO ALTER DATABASE del SET
  • 汇编器 64b 除法

    我需要一些简单的方法来在 x86 的汇编器中除以 64b 无符号整数 我的号码保存在两个 32b 寄存器 EDX EAX 中 我需要将结果放回 EDX EAX 因数为 32b 整数 请给一些代码 如果我正确解释你的问题 特别是这部分Fact
  • 发送 AVAudioRecorder 到服务器 iOS

    在过去的几天里 我试图将本地保存的声音记录上传到服务器 该服务器使用 php 文件处理它并将其保存到服务器 问题是我找不到办法做到这一点 录制声音 AVAudioRecorder 时 它保存在 NSTemporaryDirectory 中