我开始相信 iOS 是纯粹的魔法。我查看了 AVAudioPlayer 上的许多帖子以寻找解决方案,但没有一个有效。
当应用程序启动时,我有一个从 MPMoviePlayerController 开始的电影,我有一个 AVAudioPlayer 开始播放声音如下:
-(void)createAndPlayMovieFromURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType{
/* Create a new movie player object. */
player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
player.controlStyle = MPMovieControlModeDefault;
if (player)
{
/* Save the movie object. */
[self setMoviePlayerController:player];
/* Specify the URL that points to the movie file. */
[player setContentURL:movieURL];
/* If you specify the movie type before playing the movie it can result
in faster load times. */
[player setMovieSourceType:sourceType];
CGRect frame = CGRectMake(0, 0, 480, 320);
/* Inset the movie frame in the parent view frame. */
[[player view] setFrame:frame];
[player view].backgroundColor = [UIColor blackColor];
/* To present a movie in your application, incorporate the view contained
in a movie player’s view property into your application’s view hierarchy.
Be sure to size the frame correctly. */
[self.view addSubview: [player view]];
}
[[self moviePlayerController] play];
}
对于声音:
- (void)setupAudioPlayBack:(NSString *) path : (NSString *) extension{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:path
ofType:extension]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(@"Error in audioPlayer: %@",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}
}
现在让我们谈谈魔法。当播放第一部电影和声音时,声音既不响应手机上的音量控制,也不响应静音模式打开开关。
但随后第二部电影立即播放了自己的声音并且一切正常 - 静音模式打开时没有声音,如果静音模式关闭它会响应音量控制。第三部电影 - 播放也很完美。
我尝试为 MPMoviePlayerController 使用 player.useApplicationAudioSession = NO
- 解决了第一次声音不响应静音模式或音量控制的问题,但现在当第二部电影开始播放时它会卡住立即播放的声音从原来的大小缩短到大约 2 秒。
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:nil];
无论我在哪里设置它都没有帮助。
所以我的问题是 - 如何让 MPMoviePlayerController 与 AVAudioPlayer 交互而没有任何问题......
最佳答案
好吧,我真的找到了解决方案(再一次,魔法)。
当您启动 ViewController 时,您可以按如下方式设置它:
- (void)viewDidLoad
{
[self setupAudioPlayBack:@"sound1" :@"caf"];
[self playMovieFile:[self localMovieURL:@"mov1" :@"mov"]];
audioTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playAudio) userInfo:nil repeats:NO];
[super viewDidLoad];
}
playAudio 方法很简单:
- (void)playAudio{
[audioPlayer play];
}
只需 0.1 毫秒计时器就足以让一切正常(0.0 不起作用)并确保新视频不会在音频结束之前开始,否则它会破坏设置,因此您必须使计时器无效并重做再次计时。
关于ios - 当 SilentMode 开启时 AVAudioPlayer 不会静音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14129415/