2009-06-18 61 views
143

現在,iPhone 3.0 SDK是公共的,我想我可以問那些你已經玩了3.0 SDK這個問題。我想在我的應用程序中錄製音頻,但我想使用AVAudioRecorder而不是像SpeakHere所示的示例那樣採用較舊的錄製方式。 iPhone開發中心沒有任何關於如何做到這一點的例子,只能參考類。我是iPhone開發的新手,所以我正在尋找一個簡單的示例讓我開始。提前致謝。如何使用AVAudioRecorder在iPhone上錄製音頻?

回答

203

其實,有根本沒有例子。 這是我的工作代碼。錄製是由用戶在navBar上按下按鈕觸發的。 錄音使用cd質量(44100個採樣),立體聲(2個通道)線性pcm。注意:如果您想使用其他格式,尤其是編碼格式,請確保您完全理解如何設置AVAudioRecorder設置(仔細閱讀音頻類型文檔),否則您將永遠無法正確初始化它。還有一件事。在代碼中,我沒有展示如何處理計量數據,但可以輕鬆搞定。 最後,請注意截至撰寫本文時AVAudioRecorder方法deleteRecording崩潰了您的應用程序。這就是我通過文件管理器刪除記錄文件的原因。錄製完成後,我使用KVC將錄製的音頻保存爲當前編輯的對象中的NSData。

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] 


- (void) startRecording{ 

UIBarButtonItem *stopButton = [[UIBarButtonItem alloc] initWithTitle:@"Stop" style:UIBarButtonItemStyleBordered target:self action:@selector(stopRecording)]; 
self.navigationItem.rightBarButtonItem = stopButton; 
[stopButton release]; 

AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 
NSError *err = nil; 
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err]; 
if(err){ 
    NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); 
    return; 
} 
[audioSession setActive:YES error:&err]; 
err = nil; 
if(err){ 
    NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]); 
    return; 
} 

recordSetting = [[NSMutableDictionary alloc] init]; 

[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey]; 
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; 
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey]; 

[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; 
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey]; 
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey]; 



// Create a new dated file 
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0]; 
NSString *caldate = [now description]; 
recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain]; 

NSURL *url = [NSURL fileURLWithPath:recorderFilePath]; 
err = nil; 
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err]; 
if(!recorder){ 
    NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]); 
    UIAlertView *alert = 
    [[UIAlertView alloc] initWithTitle: @"Warning" 
           message: [err localizedDescription] 
           delegate: nil 
        cancelButtonTitle:@"OK" 
        otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 
    return; 
} 

//prepare to record 
[recorder setDelegate:self]; 
[recorder prepareToRecord]; 
recorder.meteringEnabled = YES; 

BOOL audioHWAvailable = audioSession.inputIsAvailable; 
if (! audioHWAvailable) { 
    UIAlertView *cantRecordAlert = 
    [[UIAlertView alloc] initWithTitle: @"Warning" 
           message: @"Audio input hardware not available" 
           delegate: nil 
        cancelButtonTitle:@"OK" 
        otherButtonTitles:nil]; 
    [cantRecordAlert show]; 
    [cantRecordAlert release]; 
    return; 
} 

// start recording 
[recorder recordForDuration:(NSTimeInterval) 10]; 

} 

- (void) stopRecording{ 

[recorder stop]; 

NSURL *url = [NSURL fileURLWithPath: recorderFilePath]; 
NSError *err = nil; 
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err]; 
if(!audioData) 
    NSLog(@"audio data: %@ %d %@", [err domain], [err code], [[err userInfo] description]); 
[editedObject setValue:[NSData dataWithContentsOfURL:url] forKey:editedFieldKey]; 

//[recorder deleteRecording]; 


NSFileManager *fm = [NSFileManager defaultManager]; 

err = nil; 
[fm removeItemAtPath:[url path] error:&err]; 
if(err) 
    NSLog(@"File Manager: %@ %d %@", [err domain], [err code], [[err userInfo] description]); 



UIBarButtonItem *startButton = [[UIBarButtonItem alloc] initWithTitle:@"Record" style:UIBarButtonItemStyleBordered target:self action:@selector(startRecording)]; 
self.navigationItem.rightBarButtonItem = startButton; 
[startButton release]; 

} 

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag 
{ 

NSLog (@"audioRecorderDidFinishRecording:successfully:"); 
// your actions here 

} 
+3

真棒,我已經迫不及待要將此代碼到我的項目。非常感謝你的回答,昨晚讓我瘋狂,試圖讓它獨立工作,但我確實很好地學習了這門課。 :) – 2009-06-18 15:24:19

+0

我認爲我已經接近讓你的代碼工作,但我正在努力與委託的東西。我對Objective C非常陌生,但仍然沒有找到正確的方法來做這樣的事情。我有我的委託試圖實現NSObject ,但我不認爲我做對了。發佈委託代碼也會太麻煩嗎?謝謝。 – 2009-06-19 01:21:42

+0

我只是最終得到它的工作,將此添加到我的代理類 @protocol AVAudioRecorder @optional - (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder; - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)記錄器成功:(BOOL)標誌; - (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)記錄器錯誤:(NSError *)錯誤; - (void)audioRecorderEndInterruption:(AVAudioRecorder *)記錄器; 它似乎工作,但我不知道這是否是最佳做法。現在我需要將其保存到本地數據存儲區,並將其重新播放。 – 2009-06-19 01:54:20

2

好吧,所以我得到的答案幫助我在正確的方向,我非常感謝。它幫助我弄清楚如何真正在iPhone上的記錄,但我想我也將包括一些有用的代碼,我從iPhone參考圖書館有:

AudioandVideoTechnologies

我用這個代碼,並把它添加到avTouch例子相當容易。使用上面的代碼示例和參考庫中的示例,我能夠很好地實現這一目標。

2

下面的鏈接,你可以找到與AVAudioRecording記錄有用的信息。在第一部分「使用音頻」的鏈接中,有一個名爲「AVAudioRecorder Class錄音」的錨點,可以引導您進入該例子。

AudioVideo Conceptual MultimediaPG

11

它真的很有幫助。我唯一的問題是記錄後創建的聲音文件的大小。我需要減小文件大小,所以我做了一些設置更改。

NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init]; 
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey]; 
[recordSetting setValue:[NSNumber numberWithFloat:16000.0] forKey:AVSampleRateKey]; 
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey]; 

文件大小從360kb減少到只有25kb(2秒記錄)。

83

雖然這是一個回答的問題(和慈祥的老人),我決定張貼其他人發現很難找到好的工作(開箱)播放和錄製比如我的完整的工作代碼 - 包括編碼,PCM通過揚聲器播放,寫在這裏提交是:

AudioPlayerViewController.h:

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

@interface AudioPlayerViewController : UIViewController { 
AVAudioPlayer *audioPlayer; 
AVAudioRecorder *audioRecorder; 
int recordEncoding; 
enum 
{ 
    ENC_AAC = 1, 
    ENC_ALAC = 2, 
    ENC_IMA4 = 3, 
    ENC_ILBC = 4, 
    ENC_ULAW = 5, 
    ENC_PCM = 6, 
} encodingTypes; 
} 

-(IBAction) startRecording; 
-(IBAction) stopRecording; 
-(IBAction) playRecording; 
-(IBAction) stopPlaying; 

@end 

AudioPlayerViewController.m:

#import "AudioPlayerViewController.h" 

@implementation AudioPlayerViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    recordEncoding = ENC_AAC; 
} 

-(IBAction) startRecording 
{ 
NSLog(@"startRecording"); 
[audioRecorder release]; 
audioRecorder = nil; 

// Init audio with record capability 
AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil]; 

NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10]; 
if(recordEncoding == ENC_PCM) 
{ 
    [recordSettings setObject:[NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey]; 
    [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey]; 
    [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey]; 
    [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; 
    [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey]; 
    [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey]; 
} 
else 
{ 
    NSNumber *formatObject; 

    switch (recordEncoding) { 
     case (ENC_AAC): 
      formatObject = [NSNumber numberWithInt: kAudioFormatMPEG4AAC]; 
      break; 
     case (ENC_ALAC): 
      formatObject = [NSNumber numberWithInt: kAudioFormatAppleLossless]; 
      break; 
     case (ENC_IMA4): 
      formatObject = [NSNumber numberWithInt: kAudioFormatAppleIMA4]; 
      break; 
     case (ENC_ILBC): 
      formatObject = [NSNumber numberWithInt: kAudioFormatiLBC]; 
      break; 
     case (ENC_ULAW): 
      formatObject = [NSNumber numberWithInt: kAudioFormatULaw]; 
      break; 
     default: 
      formatObject = [NSNumber numberWithInt: kAudioFormatAppleIMA4]; 
    } 

    [recordSettings setObject:formatObject forKey: AVFormatIDKey]; 
    [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey]; 
    [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey]; 
    [recordSettings setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey]; 
    [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; 
    [recordSettings setObject:[NSNumber numberWithInt: AVAudioQualityHigh] forKey: AVEncoderAudioQualityKey]; 
} 

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", [[NSBundle mainBundle] resourcePath]]]; 


NSError *error = nil; 
audioRecorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error]; 

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

} 
NSLog(@"recording"); 
} 

-(IBAction) stopRecording 
{ 
NSLog(@"stopRecording"); 
[audioRecorder stop]; 
NSLog(@"stopped"); 
} 

-(IBAction) playRecording 
{ 
NSLog(@"playRecording"); 
// Init audio with playback capability 
AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil]; 

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", [[NSBundle mainBundle] resourcePath]]]; 
NSError *error; 
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
audioPlayer.numberOfLoops = 0; 
[audioPlayer play]; 
NSLog(@"playing"); 
} 

-(IBAction) stopPlaying 
{ 
NSLog(@"stopPlaying"); 
[audioPlayer stop]; 
NSLog(@"stopped"); 
} 

- (void)dealloc 
{ 
[audioPlayer release]; 
[audioRecorder release]; 
[super dealloc]; 
} 

@end 

希望這將幫助一些你們的。

7

我一直在試圖讓這段代碼在過去的2個小時裏工作,雖然它在模擬器上沒有顯示錯誤,但是在設備上有一個錯誤。

事實證明,至少在我的情況,從目錄中附帶的錯誤使用(包):

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf", [[NSBundle mainBundle] resourcePath]]]; 

這是不可寫或者這樣的事情...什麼都有,除了這個事實沒有錯誤prepareToRecord

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

現在就像一個魅力:失敗...

因此,我被取而代之。

希望這可以幫助別人。

2
This is from Multimedia programming guide... 

- (IBAction) recordOrStop: (id) sender { 
if (recording) { 
    [soundRecorder stop]; 
    recording = NO; 
    self.soundRecorder = nil; 
    [recordOrStopButton setTitle: @"Record" forState: 
    UIControlStateNormal]; 
    [recordOrStopButton setTitle: @"Record" forState: 
    UIControlStateHighlighted]; 
    [[AVAudioSession sharedInstance] setActive: NO error:nil]; 
} 
else { 
    [[AVAudioSession sharedInstance] 
    setCategory: AVAudioSessionCategoryRecord 
    error: nil]; 
    NSDictionary *recordSettings = 
    [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithFloat: 44100.0], AVSampleRateKey, 
    [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey, 
    [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, 
    [NSNumber numberWithInt: AVAudioQualityMax], 
    AVEncoderAudioQualityKey, 
    nil]; 
    AVAudioRecorder *newRecorder = 
    [[AVAudioRecorder alloc] initWithURL: soundFileURL 
           settings: recordSettings 
            error: nil]; 
    [recordSettings release]; 
    self.soundRecorder = newRecorder; 
    [newRecorder release]; 
    soundRecorder.delegate = self; 
    [soundRecorder prepareToRecord]; 
    [soundRecorder record]; 
    [recordOrStopButton setTitle: @"Stop" forState: UIControlStateNormal]; 
    [recordOrStopButton setTitle: @"Stop" forState: UIControlStateHighlighted]; 
    recording = YES; 
} 
} 
0

START

NSError *sessionError = nil; 
[[AVAudioSession sharedInstance] setDelegate:self]; 
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError]; 
[[AVAudioSession sharedInstance] setActive: YES error: nil]; 
UInt32 doChangeDefaultRoute = 1; 
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute); 

NSError *error = nil; 
NSString *filename = [NSString stringWithFormat:@"%@.caf",FILENAME]; 
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:filename]; 
NSURL *soundFileURL = [NSURL fileURLWithPath:path]; 


NSDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys: 
           [NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey, 
           [NSNumber numberWithInt:AVAudioQualityMedium],AVEncoderAudioQualityKey, 
           [NSNumber numberWithInt:AVAudioQualityMedium], AVSampleRateConverterAudioQualityKey, 
           [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, 
           [NSNumber numberWithFloat:22050.0],AVSampleRateKey, 
           nil]; 

AVAudioRecorder *audioRecorder = [[AVAudioRecorder alloc] 
       initWithURL:soundFileURL 
       settings:recordSettings 
       error:&error]; 


if (!error && [audioRecorder prepareToRecord]) 
{ 
    [audioRecorder record]; 
} 

STOP

[audioRecorder stop]; 
[audioRecorder release]; 
audioRecorder = nil; 
2

低於音頻設置

wav格式
NSDictionary *audioSetting = [NSDictionary dictionaryWithObjectsAndKeys: 
           [NSNumber numberWithFloat:44100.0],AVSampleRateKey, 
           [NSNumber numberWithInt:2],AVNumberOfChannelsKey, 
           [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey, 
           [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey, 
           [NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey, 
           [NSNumber numberWithBool:0], AVLinearPCMIsBigEndianKey, 
           [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved, 
           [NSData data], AVChannelLayoutKey, nil]; 

裁判: http://objective-audio.jp/2010/09/avassetreaderavassetwriter.html

6

十分感謝@Massimo卡法洛Shaybc 我是能夠實現的任務

下面的iOS 8:

Record audio & Save

Play Saved Recording

1.新增 「AVFoundation.framework」 到您的項目

在.h文件中

2.添加以下import語句 'AVFoundation/AVFoundation.h'。

3.Define 「AVAudioRecorderDelegate」

4.Create實錄佈局,播放按鈕和其行動methids

5.Define記錄器和播放等

下面是完整的示例代碼這可能會幫助你。

ViewController.h

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

@interface ViewController : UIViewController <AVAudioRecorderDelegate> 

@property(nonatomic,strong) AVAudioRecorder *recorder; 
@property(nonatomic,strong) NSMutableDictionary *recorderSettings; 
@property(nonatomic,strong) NSString *recorderFilePath; 
@property(nonatomic,strong) AVAudioPlayer *audioPlayer; 
@property(nonatomic,strong) NSString *audioFileName; 

- (IBAction)startRecording:(id)sender; 
- (IBAction)stopRecording:(id)sender; 

- (IBAction)startPlaying:(id)sender; 
- (IBAction)stopPlaying:(id)sender; 

@end 

然後做的工作在

ViewController.m

#import "ViewController.h" 

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] 

@interface ViewController() 
@end 

@implementation ViewController 

@synthesize recorder,recorderSettings,recorderFilePath; 
@synthesize audioPlayer,audioFileName; 


#pragma mark - View Controller Life cycle methods 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
} 
- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 


#pragma mark - Audio Recording 
- (IBAction)startRecording:(id)sender 
{ 
    AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 
    NSError *err = nil; 
    [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err]; 
    if(err) 
    { 
     NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]); 
     return; 
    } 
    [audioSession setActive:YES error:&err]; 
    err = nil; 
    if(err) 
    { 
     NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]); 
     return; 
    } 

    recorderSettings = [[NSMutableDictionary alloc] init]; 
    [recorderSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey]; 
    [recorderSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; 
    [recorderSettings setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey]; 
    [recorderSettings setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; 
    [recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey]; 
    [recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey]; 

    // Create a new audio file 
    audioFileName = @"recordingTestFile"; 
    recorderFilePath = [NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName] ; 

    NSURL *url = [NSURL fileURLWithPath:recorderFilePath]; 
    err = nil; 
    recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&err]; 
    if(!recorder){ 
     NSLog(@"recorder: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]); 
     UIAlertView *alert = 
     [[UIAlertView alloc] initWithTitle: @"Warning" message: [err localizedDescription] delegate: nil 
         cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     [alert show]; 
     return; 
    } 

    //prepare to record 
    [recorder setDelegate:self]; 
    [recorder prepareToRecord]; 
    recorder.meteringEnabled = YES; 

    BOOL audioHWAvailable = audioSession.inputIsAvailable; 
    if (! audioHWAvailable) { 
     UIAlertView *cantRecordAlert = 
     [[UIAlertView alloc] initWithTitle: @"Warning"message: @"Audio input hardware not available" 
            delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     [cantRecordAlert show]; 
     return; 
    } 

    // start recording 
    [recorder recordForDuration:(NSTimeInterval) 60];//Maximum recording time : 60 seconds default 
    NSLog(@"Recroding Started"); 
} 

- (IBAction)stopRecording:(id)sender 
{ 
    [recorder stop]; 
    NSLog(@"Recording Stopped"); 
} 

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


#pragma mark - Audio Playing 
- (IBAction)startPlaying:(id)sender 
{ 
    NSLog(@"playRecording"); 

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

    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, audioFileName]]; 
    NSError *error; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; 
    audioPlayer.numberOfLoops = 0; 
    [audioPlayer play]; 
    NSLog(@"playing"); 
} 
- (IBAction)stopPlaying:(id)sender 
{ 
    [audioPlayer stop]; 
    NSLog(@"stopped"); 
} 

@end 

enter image description here

0
-(void)viewDidLoad { 
// Setup audio session 
    AVAudioSession *session = [AVAudioSession sharedInstance]; 
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; 

    // Define the recorder setting 
    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]; 

}  

- (IBAction)btnRecordDidClicked:(UIButton *)sender { 
     if (player1.playing) { 
      [player1 stop]; 
     } 

     if (!recorder.recording) { 
      AVAudioSession *session = [AVAudioSession sharedInstance]; 
      [session setActive:YES error:nil]; 

      // Start recording 
      [recorder record]; 
      [_recordTapped setTitle:@"Pause" forState:UIControlStateNormal]; 

     } else { 

      // Pause recording 
      [recorder pause]; 
      [_recordTapped setTitle:@"Record" forState:UIControlStateNormal]; 
     } 

     [_stopTapped setEnabled:YES]; 
     [_playTapped setEnabled:NO]; 

    } 

    - (IBAction)btnPlayDidClicked:(UIButton *)sender { 
     if (!recorder.recording){ 
      player1 = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil]; 
      [player1 setDelegate:self]; 
      [player1 play]; 
     } 
    } 

    - (IBAction)btnStopDidClicked:(UIButton *)sender { 
     [recorder stop]; 
     AVAudioSession *audioSession = [AVAudioSession sharedInstance]; 
     [audioSession setActive:NO error:nil]; 
    } 

    - (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{ 
     [_recordTapped setTitle:@"play" forState:UIControlStateNormal]; 

     [_stopTapped setEnabled:NO]; 
     [_playTapped setEnabled:YES]; 

    } 
相關問題