【发布时间】:2014-09-25 11:44:18
【问题描述】:
我在停止 AVPlayer 时遇到了一点困难。
我有一种方法可以同时录制和播放音乐。我正在使用 AVPlayer 播放音乐,因为我想使用 addPeriodicTimeObserverForInterval 函数。我的设置如下:
- (IBAction) recordVoice:(id)sender {
if(!recorder.isRecording){
//set up the file name to record to
NSString *recordingLocation = [self createFileName];
recordingName = recordingLocation;
NSArray *pathComponents = [NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject],
recordingLocation, nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
recordingURL = outputFileURL;
// Setup audio session
session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
error:nil];
// Define the recording settings to record as m4a
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];
[session setActive:YES error:nil];
[recorder record];
// find which song to play and initiate an AVPlayer to play it
NSString *playerLocation = self.TitleLabel.text;
NSString *path = [[NSBundle mainBundle] pathForResource:playerLocation ofType:@"m4a"];
player = [[AVPlayer alloc] initWithURL:[NSURL fileURLWithPath:path]];
lastTime = nil;
//check where the player is at and update the song lines accordingly
[player addPeriodicTimeObserverForInterval:CMTimeMake(3, 10) queue:NULL usingBlock:^(CMTime time){
NSTimeInterval seconds = CMTimeGetSeconds(time);
for (NSDictionary *item in robotR33) {
NSNumber *time = item[@"time"];
if ( seconds > [time doubleValue] && [time doubleValue] >= [lastTime doubleValue] ) {
lastTime = @(seconds);
NSString *str = item[@"line"];
[self nextLine:str];
};
}
}];
[player play];
[_recordButton setImage:[UIImage imageNamed:@"micRecording.gif"] forState:UIControlStateNormal];
}
else{
[recorder stop];
player = nil;
[session setActive:NO error:nil];
}
}
如果录音机没有录音,我会同时设置一个新的录音机 AVAudioRecorder 和一个 AVPlayer。在 AVPlayer 中,我设置了一个 AddPeriodicTimeObserverForInterval,它根据玩家的位置更新 UI。
如果录音机正在录音,我会停止录音机并将播放器设置为零。这会停止播放音频,但我注意到 addPeriodicTimeObserverInterval 仍在运行,因为 UI 继续更新。我应该完全销毁 AVPlayer,如果是,我应该怎么做?非常感谢。
另外,我在 addPeriodicTimeObserverForInterval 块中有一个警告。我正在循环一个名为robotR33 的数组。 Xcode 告诉我“在此块中强烈捕获自我可能会导致保留周期”。这可能是我的问题的一部分吗?
【问题讨论】:
标签: ios avfoundation avplayer