简体   繁体   English

使用AVAudioRecorder和AVAudioPlayer录制和播放

[英]Record and Play using AVAudioRecorder and AVAudioPlayer

I am creating an app in which user can record and play the recorded file. 我正在创建一个应用程序,用户可以在其中记录和播放记录的文件。 I am able to record and play as well, but the problem I am facing is that while playing(listening) the recording, if user presses the record button it will start recording and pressing on the stop resumes the previous recording where it was left. 我也可以进行录制和播放,但是我面临的问题是,在播放(收听)录制时,如果用户按下录制按钮,它将开始录制,而在停止位置上按则可以恢复之前录制的位置。

What I want is when user is listening to the recording and in the mean while he presses the record button, then the last recording (which he was playing) should get destroyed. 我想要的是,当用户正在收听录音时,同时按下录音按钮时,最后的录音(他正在播放)应该被销毁。

In short,I do not want to resume the last recording, I want to play the recent recording. 简而言之,我不想继续最近的录音,我想播放最近的录音。

Here is my code for recording and playback. 这是我用于记录和播放的代码。

   -(void)showStopbutton
    {
        if (flag_for_mic_button == 0)
        {
            // All in vain the following condition not making any effect palyer is resuming back
            if ([audioPlayer isPlaying])
            {
                [audioPlayer stop];
                audioPlayer = nil;
                audioPlayer = NO;
            }
            //

            [btn_Mic setImage:[UIImage imageNamed:@"stop.png"] forState:UIControlStateNormal];
            lbl_Press.hidden = TRUE;
            lbl_updateTime.hidden = FALSE;
            [self startRecording];
            flag_for_mic_button = 1;
        }
        else if (flag_for_mic_button ==1)
        {
            [self stopRecording];

            // All in vain the following condition not making any effect palyer is resuming back

            if ([audioPlayer isPlaying])
            {
                audioPlayer = NO;
                [audioPlayer stop];
                audioPlayer = nil;
            }

            //

            [btn_Mic setImage:[UIImage imageNamed:@"mic.png"] forState:UIControlStateNormal];
            lbl_Press.hidden = FALSE;
            lbl_updateTime.hidden = TRUE;
            flag_for_mic_button = 0;
        }
    }

-(void)startRecording
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
    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 numberWithInt:44100.0f] 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];
    NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
    caldate =[now description];
    recorderFilePath = [NSString stringWithFormat:@"%@/%@ MyRecording.caf",DOCUMENTS_FOLDER,caldate];
    NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
    err=nil;
    audioRecorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&err];
    [audioRecorder setDelegate:self];
    [audioRecorder prepareToRecord];
    audioRecorder.meteringEnabled = YES;

    [audioRecorder record];

    [self setTimer];
    [self hidePlaybackView];
}

-(void)stopRecording
{
    [audioRecorder stop];
    [start_Timer invalidate];
    [self showPlaybackView];

}

-(void)playSound
{
//    [self playBackTimer];

    if (!recorderFilePath)
    {
        recorderFilePath = [NSString stringWithFormat:@"%@/%@ MyRecording.caf",DOCUMENTS_FOLDER,caldate];
    }

    if(soundID)
    {
        AudioServicesDisposeSystemSoundID(soundID);
    }


    //Get a URL for the sound file
    NSURL *filePath = [NSURL fileURLWithPath:recorderFilePath isDirectory:NO];

    //Use audio sevices to create the sound
    AudioServicesCreateSystemSoundID((CFURLRef)CFBridgingRetain(filePath), &soundID);

    //Use audio services to play the sound
    AudioServicesPlaySystemSound(soundID);

    audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:filePath error:nil];

    [audioPlayer play];

    audioPlayer.delegate = self;

}

EDIT: 编辑:

-(void)showPlaybackView
{
    view_playback = [[UIView alloc]initWithFrame:CGRectMake(0, 600, 320, 80)];
    view_playback.backgroundColor = [UIColor grayColor];
    [self.view addSubview:view_playback];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.4];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
    view_playback.frame = CGRectMake(0, 325, 320, 55);
    [UIView commitAnimations];

    btn_Playback = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn_Playback setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
    btn_Playback.frame = CGRectMake(10, 10, 35, 35);
    [view_playback addSubview:btn_Playback];
    [btn_Playback addTarget:self action:@selector(playSound) forControlEvents:UIControlEventTouchUpInside];

    btn_done = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn_done setTitle:@"Done" forState:UIControlStateNormal];
    btn_done.frame = CGRectMake(265, 15, 45, 30);
    btn_done.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [view_playback addSubview:btn_done];

    [view_playback addSubview:playback_slider];


    [btn_done addTarget:self action:@selector(Done) forControlEvents:UIControlEventTouchUpInside];
}

Any help would be appreciable. 任何帮助将是可观的。

Thanks 谢谢

Try this approach : 试试这个方法:

  -(void)showStopbutton
{
        if (![audioPlayer isPlaying])
        {
            [audioPlayer start];
           // other stuff
        }

        if ([audioPlayer isPlaying])
        {
            [audioPlayer stop];
            // Delete the previous recording in the delegate method of audio player       
        }

}

I stopped the Audio Player and do not let it resume back by using the following code. 我停止了音频播放器,并且不使用以下代码让它恢复播放。

if([audioPlayer isPlaying])
{
    audioPlayer.currentTime=0;
}

Happy Coding! 编码愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM