有谁知道通过 Airplay 播放 AVPlayer 音轨时调整音量的方法?我已经尝试过 AVAudioMix 和 MPVolumeView 但它们都不起作用。我已经在 iOS 5 和 iOS 6 上尝试过,并且正在使用最新的 xcode 4.5.1。这不起作用的一个简单示例是 Apple 的 AVPlayerTestApp,它使用 setVolumeRampFromStartVolume 进行简单的淡出。这在设备上可以正常工作,但如果通过 Airplay 连接则不能。
在 ViewDidLoad 中,我加载曲目并开始播放(这全部取自 AVPlayerTestApp)
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:TRUE error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
self.mediaItems = [[[MPMediaQuery songsQuery] items] mutableCopy];
NSURL *anUrl = [[mediaItems objectAtIndex: 0] valueForProperty:MPMediaItemPropertyAssetURL];
AVAsset *asset = [AVURLAsset URLAssetWithURL:anUrl options:nil];
AVPlayerItem *myPlayerItem = [AVPlayerItem playerItemWithAsset:asset];
self.myPlayer1 = [[[AVPlayer alloc] initWithPlayerItem:myPlayerItem] retain];
[myPlayer1 play];
然后我有一个按钮,它打开一个警报视图,允许用户设置音量并打开播放
MPVolumeView *volumeView = [[[MPVolumeView alloc] initWithFrame: CGRectMake(10, 37, 260, 20)] autorelease];
UIAlertView *volumeAlert = [[UIAlertView alloc] initWithTitle:@"Volume" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[volumeView sizeToFit];
[volumeAlert addSubview:volumeView];
[volumeAlert show];
[volumeAlert release];
然后是淡出当前播放曲目的另一个按钮
AVAsset *asset = [myPlayer1.currentItem asset];
NSArray *keys = [NSArray arrayWithObject:@"tracks"];
[asset loadValuesAsynchronouslyForKeys:keys completionHandler:^(void) {
NSError *error = nil;
AVKeyValueStatus trackStatus = [asset statusOfValueForKey:@"tracks" error:&error];
CMTime currentTime;
switch (trackStatus) {
case AVKeyValueStatusLoaded:
if(myPlayer1)
{
NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeAudio];
NSMutableArray * allAudioParams = [NSMutableArray array];
for (AVAssetTrack *t in tracks) {
AVMutableAudioMixInputParameters *params =[AVMutableAudioMixInputParameters audioMixInputParameters];
float fadeOutSeconds = 5;
currentTime = [myPlayer1 currentTime];
[params setVolumeRampFromStartVolume: 1.0 toEndVolume: 0.0 timeRange: CMTimeRangeMake(currentTime, CMTimeMakeWithSeconds(fadeOutSeconds, 1))];
[params setTrackID:[t trackID]];
[allAudioParams addObject:params];
}
AVMutableAudioMix * zeromix = [AVMutableAudioMix audioMix];
[zeromix setInputParameters:allAudioParams];
[myPlayer1.currentItem setAudioMix:zeromix];
}
break;
case AVKeyValueStatusFailed:
// error occured loading AVAsset
NSLog(@"error occured loading AVAsset");
break;
case AVKeyValueStatusCancelled:
// loading of the AVAsset was cancelled
NSLog(@"loading of the AVAsset was cancelled");
break;
default:
break;
}
}];
这在设备上按预期工作,并在点击按钮时减弱音量。但是,如果打开 Airplay,则无法更改音量。使用 MPMoviePlayController 我可以做淡化自己,这在 Airplay 上工作,但 AVPlayer 的延迟比 Airplay 少,所以我宁愿使用它。
非常感谢任何帮助。