AVFoundation:在播放循环之间添加静音暂停

时间:2012-04-06 20:47:26

标签: ios xcode avfoundation avaudioplayer

我想循环录制的声音3次,但想要在循环之间静音一秒钟,我该如何解决这个问题呢?我的play_button代码:

-(IBAction) play_button_pressed{

AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error];

[avPlayer setNumberOfLoops: 2];
[avPlayer play];

}

1)我可以添加到此方法中添加一秒钟的静音吗?

2)如果没有,有没有办法在实际录音中添加第二个静音?

编辑:谢谢;我有一个解决方案,一次重复声音,暂停2秒;它不会无限循环,你能说出我错过的东西吗?

-(IBAction) play_button_pressed{

AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error];

//[avPlayer setNumberOfLoops: 2];
avPlayer.delegate = self;
[avPlayer prepareToPlay];
[avPlayer play];

}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)avPlayer successfully:(BOOL)flag
{
NSLog(@"audioPlayerDidFinishPlaying");
tm = [NSTimer scheduledTimerWithTimeInterval:2.0
                                 target:self
                               selector:@selector(waitedtoplay)
                               userInfo:nil 
                                repeats:NO];
}

-(void) waitedtoplay
{
    AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error];
[tm invalidate];
[avPlayer prepareToPlay];
[avPlayer play];
NSLog(@"waitedtoplay");
}

1 个答案:

答案 0 :(得分:1)

据我所知,AVAudioPlayer的方法在播放循环之间没有“沉默”。

当我进行相同类型的循环时,我使用了AVAudioPlayerDelegate和timer中定义的回调方法。

在头文件中,声明如下使用AVAudioPlayerDelegate;

@interface xxxxController : UIViewController
<AVAudioPlayerDelegate>{

当avPlayer结束播放声音时, 将调用“audioPlayerDidFinishPlaying”方法。

然后调用方法等待一段时间,例如;

-(void) wait{
float seconds = 2.0f;
tm = [NSTimer scheduledTimerWithTimeInterval:seconds
                                      target:self
                                    selector:@selector(waitedtoplay) 
                                    userInfo:nil 
                                     repeats:NO];
}

并且,在方法“waitedtoplay”中,调用next [avPlayer play]

-(void) waitedtoplay{
    [tm invalidate];
    [avPlayer play];
}

这是一个永无止境的循环,所以请添加计数器来限制loop = 3的数量。

编辑

在您添加为“waitedtoplay”的方法中,您错过了设置“avplayer.delegate = self”。 因此,AVAudioPlayer不会调用“audioPlayerDidFinishPlaying”。

-(void) waitedtoplay
{
AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error];
[tm invalidate];
avPlayer.delegate = self; <<=== MISSING !
[avPlayer prepareToPlay];
[avPlayer play];
NSLog(@"waitedtoplay");
}

请按上面的说法添加,它会无限重复......

相关问题