ios - 以 AAC 格式录制和播放音频 iOS 5 +

标签 ios avaudioplayer avaudiorecorder aac

我想在 iOS 中录制声音并播放。我还想将录制的文件发送到服务器。我有一个问题,录制的文件也必须在 ANDROID 设备上播放。所以我尝试使用MP3。但 AVAudioRecorder 不允许 MP3 格式进行录音。所以我用的是AAC。但它不起作用。这是我的代码

    -(void)initializeAudioRecorder {

    self.btnPlayRecording.enabled = NO;
    self.btnStopRecording.enabled = NO;

    // Get sound file URL in which recording is saved
    NSURL *soundFileURL = [NSURL fileURLWithPath:[self soundFilePath]];

    // Set settings for audio recording
    NSDictionary *audioRecordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithInt:AVAudioQualityMin],AVEncoderAudioQualityKey,
        [NSNumber numberWithInt:16],AVEncoderBitRateKey,
        [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
        [NSNumber numberWithFloat:44100.0],AVSampleRateKey,
        [NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey, nil];

    NSError *error = nil;
    self.audioRecorder = [[AVAudioRecorder alloc]
                     initWithURL:soundFileURL
                     settings:audioRecordSettings
                     error:&error];

    if (error)
    {
        NSLog(@"error: %@", [error localizedDescription]);
    } 
    else {
        if (![self.audioRecorder prepareToRecord]) {
            NSLog(@"Failed to prepare recording");
        }
    }
}

    #pragma mark - Get Sound File Path

-(NSString*)soundFilePath {

    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDirPath = [dirPaths objectAtIndex:0];
    NSString *soundFilePath = [docsDirPath stringByAppendingPathComponent:@"testSound.aac"];
    return soundFilePath;
}


#pragma mark - IBAction Methods

- (IBAction)btnStartRecordingTapped:(id)sender {

    if (!self.audioRecorder.recording) {
        self.btnPlayRecording.enabled = NO;
        self.btnStopRecording.enabled = YES;
        [self.audioRecorder record];
    }
}

- (IBAction)btnStopRecordingTapped:(id)sender {

    self.btnStopRecording.enabled = NO;
    self.btnPlayRecording.enabled = YES;
    self.btnStartRecording.enabled = YES;
}

- (IBAction)btnPlayRecordingTapped:(id)sender {

    if (!audioRecorder.recording) {
        self.btnStopRecording.enabled = YES;
        self.btnStartRecording.enabled = NO;
        NSError *error = nil;

        self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:self.audioRecorder.url error:&error];
        self.audioPlayer.delegate = self;

        if (error) {
            NSLog(@"Error occured while playing recorded audio.\nError:- %@",[error localizedDescription]);
        }
        else {
            [self.audioPlayer play];
        }

    }
}

#pragma mark - AVAudioPlayer Delegate MEthods

/* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"In %s",__PRETTY_FUNCTION__);
    self.btnStartRecording.enabled = YES;
    self.btnStopRecording.enabled = NO;
}

/* if an error occurs while decoding it will be reported to the delegate. */
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    NSLog(@"In %s",__PRETTY_FUNCTION__);
    NSLog(@"audioPlayerDecodeError:- %@",[error localizedDescription]);
}

#pragma mark - AVAudioRecorder Delegate MEthods

/* audioRecorderDidFinishRecording:successfully: is called when a recording has been finished or stopped. This method is NOT called if the recorder is stopped due to an interruption. */
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    NSLog(@"In %s",__PRETTY_FUNCTION__);
}

/* if an error occurs while encoding it will be reported to the delegate. */
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
    NSLog(@"In %s",__PRETTY_FUNCTION__);
    NSLog(@"audioRecorderEncodeError:- %@",[error localizedDescription]);
}

但是上面的代码没有录制音频。文件在 DOCS 目录中创建。但当我尝试玩它时,它不起作用。我什么也听不到。

我的代码有什么问题吗? 另外,是否有任何库可以录制和播放可在 iOS + Android 上播放的格式的音频?谢谢

最佳答案

这对我有用:

  1. 确保设备音量足够高:

    MPMusicPlayerController * musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
    if (musicPlayer.volume < 1.0) {
          musicPlayer.volume = 1; // device volume will be changed to maximum value
    }
    musicPlayer = nil;
    
  2. 使用 AVAudioSession:

    AVAudioPlayer * meinPlayer = [[AVAudioPlayer alloc]
                      initWithContentsOfURL:soundFileURL
                      error:&error];
    meinPlayer.delegate = self;
    
    [meinPlayer prepareToPlay]
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    [meinPlayer play];
    

关于ios - 以 AAC 格式录制和播放音频 iOS 5 +,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12001791/

相关文章:

ios - AVAudioFoundation升级至iOS 5.0

ios - CLLocation 接受大于或小于其最小值和最大值的经度和纬度

javascript - Paypal 支付转账确认API

swift - 即使有公差,AVPlayer Seek 也不准确Before : kCMTimeZero

java - 如何在android中的项目单击中从 ListView 中获取歌曲

iOS 音频文件无法在桌面网络浏览器中播放

ios - iPhone 4s 和 iPhone 5 中的位置更新无法在后台模式 iOS 7.0 中运行,而手机处于理想状态

ios - 在 Swift 中使用 uiimagePickerController 在同一 View Controller 中选取两个不同的图像

xcode - 为什么音频在模拟器中有效,而在我的 iPad 上无效?

ios - AVAssetExportSession exportAsynchronouslyWithCompletionHandler : method Not Called