Lin*_*ing 2 avfoundation ios avplayer
我在停止 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];
}
}
Run Code Online (Sandbox Code Playgroud)
如果录音机没有录音,我会设置一个新的录音机 AVAudioRecorder 和一个 AVPlayer。在 AVPlayer 中,我设置了一个 AddPeriodicTimeObserverForInterval,它根据玩家的位置更新 UI。
如果录音机正在录音,我会停止录音并将播放器设置为 nil。这会停止播放音频,但我注意到 addPeriodicTimeObserverInterval 仍在运行,因为 UI 继续更新。我应该完全销毁 AVPlayer,如果是这样,我应该怎么做?提前谢谢了。
另外顺便说一句,我在 addPeriodicTimeObserverForInterval 块中有一个警告。我正在遍历一个名为robotR33 的数组。Xcode 告诉我“在这个块中强烈捕获自我可能会导致一个保留周期”。这可能是我的问题的一部分吗?
完成播放后,需要将观察者从播放器中移除。
添加[player removeTimeObserver:self.timeObserver]作品。
| 归档时间: |
|
| 查看次数: |
3091 次 |
| 最近记录: |