首页 文章

调整播放AVPlayer的音量

提问于
浏览
18

在当前播放AVPlayer项目上获取音量变量的唯一方法是遵循此过程;

  • 卸载当前正在播放的AVPlayerItem资源

  • 抓取该AVPlayerItem的当前播放时间

  • 将资产加载到新的AVPlayerItem中

  • 用新的AVPlayerItem替换当前的AVPlayerItem

  • 等待AVIlayer上的currentItem更改

  • 准备好AudioMix并寻找之前的播放时间

我是否错过了某个地方的基本原则,或者仅仅是为了简单地管理音量水平?

我无法使用AVAudioPlayer,因为我需要将iTunes曲目加载到播放器中 .

4 回答

  • 2

    您可以使用此处描述的方法在播放时更改音量:

    http://developer.apple.com/library/ios/#qa/qa1716/_index.html

    虽然文章的文字似乎暗示它只能用于静音音频,但您实际上可以将音量设置为您喜欢的任何音量,并且您可以在音频播放后进行设置 . 例如,假设您的AVAsset实例称为“资产”,您的AVPlayerItem实例称为“playerItem”,并且您要设置的卷称为“volume”,以下代码应该执行您想要的操作:

    NSArray *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
    
    NSMutableArray *allAudioParams = [NSMutableArray array];
    for (AVAssetTrack *track in audioTracks) {
      AVMutableAudioMixInputParameters *audioInputParams = 
        [AVMutableAudioMixInputParameters audioMixInputParameters];
      [audioInputParams setVolume:volume atTime:kCMTimeZero];
      [audioInputParams setTrackID:[track trackID]];
      [allAudioParams addObject:audioInputParams];
    }
    
    AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
    [audioMix setInputParameters:allAudioParams];
    
    [playerItem setAudioMix:audioMix];
    
  • 4

    您是否尝试过准备AVMutableAudioMix并在AVPlayerItem仍在播放时将其设置在AVPlayerItem上?您应该能够向AVPlayer询问其currentItem,它可以提供AVMutableAudioMix的AVMutableAudioMixInputParame应该引用的轨道 . 您为混合物提供的时间与混合物的施加时间相关 .

  • 21
    - (IBAction)sliderAction:(id)sender {
    NSLog(@"slider :%f ", self.mixerSlider.value);
    
    NSArray *audioTracks = [self.videoHandler.videoAsset tracksWithMediaType:AVMediaTypeAudio];
    
    // Mute all the audio tracks
    NSMutableArray *allAudioParams = [NSMutableArray array];
    for (AVAssetTrack *track in audioTracks) {
        AVMutableAudioMixInputParameters *audioInputParams =[AVMutableAudioMixInputParameters audioMixInputParameters];
        [audioInputParams setVolume:self.mixerSlider.value atTime:kCMTimeZero];
        [audioInputParams setTrackID:[track trackID]];
        [allAudioParams addObject:audioInputParams];
    }
    AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
    [audioMix setInputParameters:allAudioParams];
    
    [[self.mPlayer currentItem] setAudioMix:audioMix]; }
    

    滑块值更改后调用此方法 . 你可以在视频播放时调用它 .

  • 0

    请注意,原始问题(和几个答案)中描述的基于_2916699的方法仅适用于基于文件的资产,而不适用于流媒体 .

    这在Apple编写的文档中有详细说明,此处:

    https://developer.apple.com/library/content/qa/qa1716/_index.html

    当我尝试使用流音频执行此操作时,我没有收到任何从AVAsset的 tracks(withMediaType:) 方法(Swift)返回的曲目 .

相关问题