简体   繁体   English

关闭AVPlayer的音频播放?

[英]Turn off audio playback of AVPlayer?

I have a AVPlayer with AVPlayerItem. 我有一个AVPlayer与AVPlayerItem。 What i want is to turn off the audio playback off AVPlayer. 我想要的是关闭AVPlayer音频播放。 I want play just video. 我想播放视频。

Can someone help me? 有人能帮我吗? Thank you! 谢谢!

    self.avPlayerItem = [AVPlayerItem playerItemWithURL:self.videoUrl];
    self.avPlayer = [AVPlayer playerWithPlayerItem:self.avPlayerItem];
    [self.avPlayer play];
    self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;


    self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
    self.avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidPlayToEndTime:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:self.avPlayerItem];


    CGRect screenRect = [[UIScreen mainScreen] bounds];

    self.avPlayerLayer.frame = CGRectMake(0, 0, screenRect.size.width , screenRect.size.height );
    [self.view.layer insertSublayer:self.avPlayerLayer atIndex:0];

AVPlayer have option AVPlayer有选择权

@property (nonatomic, getter=isMuted) BOOL muted NS_AVAILABLE(10_7, 7_0);

You can write 你可以写

- (void) muteSound:(BOOL)mute
{
    self.avPlayer.muted = mute;
}

And use it, how you want 并使用它,你想要的

- (void) startPlayingVideo
{

    [self muteSound:YES];

    //other code

} 

As @Tung Fam's answer suggests, you can easily do this in your App to mute a video- 正如@Tung Fam的回答所示,你可以在你的应用程序中轻松地做到这一点来静音视频 -

player.isMuted = true

Handling all the Use Cases: 处理所有用例:

You may run a video on mute using the code above, the problem is, if you simply use isMuted = true (for let's say the video preview) it will work, but your app will "hijack" the AVAudioSession from the Operating system, which means if the user was, lets say, listening to music (spotify or apple music), their music would get interrupted. 你可以使用上面的代码静音运行一个视频,问题是,如果你只是使用isMuted = true (比如说视频预览)它会起作用,但你的应用程序将“劫持”操作系统中的AVAudioSession ,意味着如果用户说,听音乐(spotify或苹果音乐),他们的音乐就会被打断。 That is because your App will have a default setup of AVAudioSession to AVAudioSessionCategorySoloAmbient , which means that your app will ALWAYS interrupt all audio sessions that is running in the background as soon as it starts playing a video, muted or un-muted . 这是因为您的应用程序将AVAudioSession的默认设置为AVAudioSessionCategorySoloAmbient ,这意味着您的应用程序将在开始播放视频时静音中断所有在后台运行的音频会话,静音或取消静音 This may not be a very pleasing user experience and lead to confusion. 这可能不是一个非常令人愉快的用户体验并导致混淆。

What you may want to do is, show your video muted as a preview, while the user continues to play their song in the background. 您可能想要做的是,将您的视频静音显示为预览,同时用户继续在后台播放他们的歌曲。 When user goes to full screen with your app's video, any background audio must "pause" or be "interrupted" essentially your app taking over the AVAudioSession . 当用户使用您应用的视频进入全屏时,任何背景音频必须“暂停”或“中断”,基本上您的应用程序将接管AVAudioSession And then once you are done playing your video let the "interrupted" background music (example: Spotify, Apple Music etc.) to resume. 然后,一旦完成播放视频,就可以恢复“中断”的背景音乐(例如:Spotify,Apple Music等)。 The steps below achieves exactly how Twitter's app handles videos and background music- 以下步骤完全实现了Twitter的应用程序处理视频和背景音乐的方式 -

  1. In your AppDelegate in didFinishLaunchingWithOptions method make sure your app is not interrupting any background music. didFinishLaunchingWithOptions方法的AppDelegate中,确保您的应用不会中断任何背景音乐。 Now since your videos would be running in "mute" you can simply mixWithOthers . 现在,由于您的视频将以“静音”方式运行,因此您可以简单地mixWithOthers

      do{ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [.mixWithOthers]) try AVAudioSession.sharedInstance().setActive(true) }catch{//some meaningful exception handling} 
  2. When your App starts to play your video Full screen (un-muted/with sound), you must now interrupt any background music. 当您的应用程序开始播放您的视频全屏(未静音/有声)时,您现在必须中断任何背景音乐。 For that, before your player.play() you can set the AVAudioSession again, like so- 为此,在你的player.play()之前你可以再次设置AVAudioSession ,就像这样 -

     do{ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: []) try AVAudioSession.sharedInstance().setActive(true) }catch{//some meaningful exception handling} 

    this will basically pause/interrupt any background audio in progress and let your video play with sound. 这将基本上暂停/中断正在进行的任何背景音频,让您的视频播放声音。

  3. Once your video is done playing with sound, you must now let the AVAudioSession know that it can resume any audio session that was interrupted by you (ie Spotify, apple music, map navigation instructions etc.). 一旦你的视频播放AVAudioSession声音,你现在必须让AVAudioSession知道它可以恢复被你打断的任何音频会话(即Spotify,苹果音乐,地图导航指令等)。 To do that, once your video stops playing you can do this- 要做到这一点,一旦你的视频停止播放,你可以这样做 -

     do{ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [.mixWithOthers]) try AVAudioSession.sharedInstance().setActive(false, with: AVAudioSessionSetActiveOptions.notifyOthersOnDeactivation) }catch{//some meaningful exception handling} 

There's a lot more options available on how to handle AVAudioSession and here's the documentation. 有关如何处理AVAudioSession更多选项, 这里有文档。 And here are Apple's guidelines on using AVAudioSession for different type of apps. 这里是苹果公司的使用指南AVAudioSession针对不同类型的应用程序。


This is just a very basic explanation on how AVAudioSession can be used, but depending on your app's functionality there may be a need to use KVOs, AppDelegate methods (for app going to background and or coming to foreground and so on) to set the AVAudioSession appropriately. 这只是关于如何使用AVAudioSession一个非常基本的解释,但根据您的应用程序的功能,可能需要使用KVO,AppDelegate方法(用于应用程序转到后台和/或前台等)来设置AVAudioSession适当。 Further caveat is that you really need to play around with all the options on AVAudioSession since it may not work the way you think it should so it could become a little grueling. 进一步需要注意的是,你真的需要玩AVAudioSession上的所有选项,因为它可能不会像你想象的那样工作,所以它可能会变得有点费力。 Even more caveat is that surprisingly i've found very little online that goes into detail with AVAudioSession except for Apple's documentation and a few questions here on SO here and there. 更值得注意的是,令人惊讶的是,我发现AVAudioSession在线细节AVAudioSession除了Apple的文档以及这里和那里的一些问题。 Bottom line is - if your app deals with Audio/Videos then it is HIGHLY recommended to handle AVAudioSession appropriately based on Apple's playbook of " Audio Guidelines By App Type ", maybe not when you launch your app but definitely as your app matures and becomes more stable. 底线是 - 如果您的应用处理音频/视频,那么强烈建议根据Apple的“ 应用类型的音频指南 ”的剧本来适当地处理AVAudioSession ,可能不是在您启动应用时,但肯定是因为您的应用程序成熟并变得更多稳定。

In case someone is looking for Swift 4 : 如果有人在寻找Swift 4

player.isMuted = true // To mute the sound
player.isMuted = false // To un-mute the sound

Side note: muting the video does not reset the video sound to start. 旁注:静音视频不会重置视频声音以启动。 It works as just a common sense mute feature. 它只是一个常识性的静音功能。

You can mute the audio by implementing following code into viewDidLoad() . 您可以通过在viewDidLoad()实现以下代码来静音音频。

AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[self myAssetURL] 
options:nil];
NSArray *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio]; 

// Mute all the audio 
tracksNSMutableArray *allAudioParams = [NSMutableArray array];

for (AVAssetTrack *track in audioTracks) {    
AVMutableAudioMixInputParameters *audioInputParams 
=[AVMutableAudioMixInputParameters audioMixInputParameters];   

[audioInputParams setVolume:0.0 atTime:kCMTimeZero];  

[audioInputParams setTrackID:[track trackID]];    [allAudioParams 
addObject:audioInputParams];}

AVMutableAudioMix *audioZeroMix = 
[AVMutableAudioMix audioMix];
[audioZeroMix setInputParameters:allAudioParams];

Following links may help you. 以下链接可以帮助您。

  1. https://goo.gl/WYJNUF https://goo.gl/WYJNUF
  2. https://goo.gl/epHNGs https://goo.gl/epHNGs

You can add this in the AppDelegate didFinishLaunchingWithOptions. 您可以在AppDelegate didFinishLaunchingWithOptions中添加它。 If you don't want your video to stop the sound that is currently played on other apps (even if your video player is set to mute) 如果您不希望视频停止当前在其他应用上播放的声音(即使您的视频播放器设置为静音)

func setAudioMix(){
    do{
        try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: [.mixWithOthers])
        try AVAudioSession.sharedInstance().setActive(true)
    }catch{
        print("something went wrong")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM