我正在尝试使用MPMoviePlayerController或AVPlayer在我的应用程序中播放短视频。问题是(因为我的视频没有任何声音),我不想干扰其他应用程序在后台播放的声音。我试着和AVAudioSession玩
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[audioSession setActive:YES error:nil];但我没那么走运。视频一开始播放,背景中的音乐就会停止。我甚至尝试将音频会话设置为非活动状态:
[[AVAudioSession sharedInstance] setActive:NO withOptions: AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];但在这种情况下,声音会停止半秒,然后继续播放,视频播放器也会停止播放。有没有办法实现我想要做的事情?谢谢。
发布于 2016-02-08 22:53:41
我认为这对你来说已经不再重要了,但可以与其他人相关。
没有什么可做的,但这里有一些变通方法。重点是,当你初始化视频播放器时,将音频会话类别设置为环境,在这种情况下,它不会中断其他应用程序中的音频会话。然后,如果您需要“取消静音”视频,您可以设置音频会话类别为默认(独奏环境)。它将中断其他应用程序中的音频会话,并恢复播放带有声音的视频。
示例:
- (void)initPlayer {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient withOptions:0 error:nil];
// some init logic
// e.g:
//
// _playerItem = [AVPlayerItem playerItemWithAsset:[AVAsset assetWithURL:_URL]];
// _player = [AVPlayer playerWithPlayerItem:_playerItem];
// _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
//
// etc.
}
- (void)setMuted:(BOOL)muted {
if (!muted) {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient withOptions:0 error:nil];
}
self.player.muted = muted;
}附注:我假设,FB应用程序正在做类似的事情:当视频开始播放静音时,它不会中断其他应用程序的音频,但当用户按下视频时,它将全屏播放声音,此时将有该视频的活动音频会话,所有其他应用程序将停止播放音频。
发布于 2014-10-21 06:53:20
你在测试你的音乐bkg应用吗?如果不是,那么答案可能是大多数音乐应用程序都包含:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleAudioSessionInterruption:)
name:AVAudioSessionInterruptionNotification
object:aSession];和实现方式,如:
- (void) handleAudioSessionInterruption:(NSNotification*)notification
{
NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
.....code....
switch (interruptionType.unsignedIntegerValue) {
case AVAudioSessionInterruptionTypeBegan:{
// stop playing
} break;
case AVAudioSessionInterruptionTypeEnded:{
// continue playing
} break;
default:
break;
}
}因此,当中断结束时,它们会停止播放并开始播放。(适用于来电等)
发布于 2019-10-03 21:52:20
很棒的答案!对于感兴趣的人来说,这是一个Swift 5转换。
try? AVAudioSession.sharedInstance().setCategory(.ambient)https://stackoverflow.com/questions/26475114
复制相似问题