Как я могу получить положение AVPlayer y, высоту, ширину в AVPlayerLayer в цели c

Я хочу получить положение видео в AVPlayer x, y и высоту, ширину отображаемого видео в AVPlayerLayer.

введите здесь описание изображения

Мой код:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Video" ofType:@"mp4"];
NSURL *url=[[NSURL alloc]initFileURLWithPath:path];
AVPlayer *av = [[AVPlayer alloc] initWithURL:url];
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:av];
[layer setFrame:self.view.frame];
[self.view.layer addSublayer:layer];
[av play];

person sohil    schedule 21.07.2017    source источник
comment
попробуйте это... stackoverflow.com/questions/35650064/   -  person Gaya3    schedule 25.07.2017


Ответы (4)


Вы можете сделать так.

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Video" ofType:@"mp4"];
    NSURL *url=[[NSURL alloc]initFileURLWithPath:path];

    av = [[AVPlayer alloc] initWithURL:url];
    layer = [AVPlayerLayer playerLayerWithPlayer:av];
    [layer setFrame:self.view.frame];
    [self.view.layer addSublayer:layer];
    [av play];

    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
    AVAssetTrack *track = [tracks objectAtIndex:0];
    CGSize mediaSize = track.naturalSize;



    UIInterfaceOrientation orintation = [self orientationForTrack:asset];

    if (orintation == UIInterfaceOrientationLandscapeRight) {
        NSLog(@"UIInterfaceOrientationLandscapeRight");
        float videoWidth  = mediaSize.width;
        float videoHeight = mediaSize.height;
        float calVideoHeight =  (videoHeight * ScreenWidth)/videoWidth;

        NSLog(@"Video X      : 0");
        NSLog(@"Video Y      : %f",(ScreenHeight/2)-(calVideoHeight/2));
        NSLog(@"Video Width  : %f",ScreenWidth);
        NSLog(@"Video Height : %f",calVideoHeight);
    }
    else if (orintation == UIInterfaceOrientationLandscapeLeft) {
        NSLog(@"UIInterfaceOrientationLandscapeLeft");
        float videoWidth  = mediaSize.width;
        float videoHeight = mediaSize.height;
        float calVideoHeight =  (videoHeight * ScreenWidth)/videoWidth;

        NSLog(@"Video X      : 0");
        NSLog(@"Video Y      : %f",(ScreenHeight/2)-(calVideoHeight/2));
        NSLog(@"Video Width  : %f",ScreenWidth);
        NSLog(@"Video Height : %f",calVideoHeight);
    }
    else if (orintation == UIInterfaceOrientationPortraitUpsideDown) {
        NSLog(@"UIInterfaceOrientationPortraitUpsideDown");
        float videoWidth  = mediaSize.width;
        float videoHeight = mediaSize.height;
        float calVideoWidth =  (videoWidth * ScreenHeight)/videoHeight;

        NSLog(@"Video X      : 0");
        NSLog(@"Video Y      : 0");
        NSLog(@"Video Width  : %f",calVideoWidth);
        NSLog(@"Video Height : %f",ScreenHeight);

    }
    else if (orintation == UIInterfaceOrientationPortrait) {
        NSLog(@"UIInterfaceOrientationPortrait");
        float videoWidth  = mediaSize.width;
        float videoHeight = mediaSize.height;
        float calVideoWidth =  (videoWidth * ScreenHeight)/videoHeight;

        NSLog(@"Video X      : 0");
        NSLog(@"Video Y      : 0");
        NSLog(@"Video Width  : %f",calVideoWidth);
        NSLog(@"Video Height : %f",ScreenHeight);
    }


- (UIInterfaceOrientation)orientationForTrack:(AVAsset *)asset {
    AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
    CGSize size = [videoTrack naturalSize];
    CGAffineTransform txf = [videoTrack preferredTransform];

    if (size.width == txf.tx && size.height == txf.ty)
        return UIInterfaceOrientationLandscapeRight;
    else if (txf.tx == 0 && txf.ty == 0)
        return UIInterfaceOrientationLandscapeLeft;
    else if (txf.tx == 0 && txf.ty == size.width)
        return UIInterfaceOrientationPortraitUpsideDown;
    else
        return UIInterfaceOrientationPortrait;
}
person amit_donga    schedule 24.07.2017

Вы можете получить размер видео:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Video" ofType:@"mp4"];
NSURL *url=[[NSURL alloc]initFileURLWithPath:path]
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
AVAssetTrack *track = [tracks objectAtIndex:0];
CGSize mediaSize = track.naturalSize;

И рассчитать положение видео на экране.

person Evgen Litvinenko    schedule 21.07.2017
comment
Здравствуйте @Evgen Litvinenko, как рассчитать положение X и Y. - person sohil; 21.07.2017
comment
ваше видео будет в центре, верно? так что вы знаете размер видео и положение. - person Evgen Litvinenko; 21.07.2017
comment
Привет, @Evgen Litvinenko, размер моего видео 1280 x 720. У меня есть несколько видео разного размера. Горизонтальное или вертикальное. Оба. если вы знаете, как рассчитать позицию, пожалуйста, дайте мне этот код. - person sohil; 21.07.2017

Вы можете использовать свойство videoRect для AVPlayerLayer: https://developer.apple.com/documentation/avfoundation/avplayerlayer/1385745-videorect

person Michał Ciuba    schedule 24.07.2017
comment
это даст мне AVPlayerLayer Rect, а мой AVPlayerLayer имеет полный размер на экране, поэтому он даст границы просмотра. Я хочу, чтобы Rect воспроизводил видео на AVPlayerLayer. - person sohil; 24.07.2017

Вы можете добавить наблюдателя "ключ-значение" в AVPlayerLayer и использовать измененное значение для определения размера и местоположения видео.

в свифт 4

 yourAVPlayerLayer.addObserver(self,
                              forKeyPath: #keyPath(AVPlayerLayer.videoRect),
                              options: [.old, .new],
                              context:nil)

    override func observeValue(forKeyPath keyPath: String?,
                                   of object: Any?,
                                   change: [NSKeyValueChangeKey : Any]?,
                                   context: UnsafeMutableRawPointer?) {

          if keyPath == #keyPath(AVPlayerLayer.videoRect){

                if let size = change?[.newKey] as? CGRect {
                    print("X:",size.origin.x," Y:",size.origin.y," width:",size.width," height:",size.height);

                }
            }
    }
person Zain Ali    schedule 26.01.2019