Reproducir Videos de YouTube con Octane Video: Usando MVVM

Hace unos días me había surgido la idea de implementar videos de YouTube en Xamarin, alguien me hablo de esta librería Octane Xam Video, la misma tiene una buena documentación, pero, a la hora de implementar videos de YouTube, tiene algunos problemas, en este post, les enseñare mi solución y la forma de como implementarlo con MVVM.

Vamos a crear un proyecto Xamarin Form en blanco y dentro del proyecto compartido vamos a crear las siguientes carpetas:

  • Views
  • ViewModels
  • Models

Luego de que tenemos estas carpetas, vamos a ir a nuestro manejador de paquetes en el lugar de siempre: Click derecho en la solución del proyecto > Manejador de paquetes para la solucion y seleccionamos la pestaña de Buscar.

En el Buscador vamos a escribir Octane.Xam.VideoPlayer y vamos a seleccionar el siguiente paquete y lo instalaremos en los tres proyectos.

Luego vamos a ir al archivo MainActivity.cs de nuestro proyecto Android y lo abriremos y antes del Loadaplication(new App()); vamos a colocar el siguiente codigo: FormsVideoPlayer.Init();, nos pedira que agreguemos una referencia que dice Octane.Xamarin.Form.VideoPlayer.Android.

Hacemos lo mismo en nuestro proyecto iOS en el archivo AppDelegate.cs, antes de LoadApplication(new App());, colocaremos FormsVideoPlayer.Init(); y le nos pedira agregar la referencia Octane.Xamarin.Forms.VideoPlayer.iOS, la seleccionamos y listo.

Ahora vamos a crear otra carpeta llamada Converters dentro de nuestro proyecto compartido y agregaremos un archivo C# llamado YouTubeVideoIdConverter.cs y agregaremos dentro de el, el siguiente codigo (Copiar y Pegar), el archivo apareceran unos errores, mantener el archivo abierto, mas adelante les indico.

Luego, dentro de la carpeta Models, crearemos una clase con el nombre PlayerResponse.cs y copiaremos y pegaremos el siguiente codigo.

Luego de hacer esto, volvemos a YouTubeVideoIdConverter.cs para corregir lo que nos falta, aqui simplemente veremos que nos indica agregar una referencia a la carpeta Models para poder leer el archivo que creamos anteriormente y agregar un paquete NewtonSoft para hacer la deserializacion que estamos realizando en ese archivo, le damos a instalar y continuamos.

Ahora agregaremos un Content Page dentro de la carpeta Views, pueden asignarle el nombre que deseen, yo le llamare YouTubeVideo y en la propiedades de nuestro Xaml agregaremos lo siguiente.

xmlns:o="clr-namespace:Octane.Xamarin.Forms.VideoPlayer;assembly=Octane.Xamarin.Forms.VideoPlayer"
xmlns:me="clr-namespace:OctanePost.Converters;assembly=OctanePost"

Y le agregaremos el recurso del converter.

<ContentPage.Resources>
        <ResourceDictionary>
            <me:YouTubeVideoIdConverter x:Key="ReturnUrl" />
        </ResourceDictionary>
</ContentPage.Resources>

Luego agregamos nuestro reproductor.

<o:VideoPlayer x:Name="videoPlayer"  Source="{Binding IdYouTube,Converter={StaticResource ReturnUrl}}" FillMode="ResizeAspectFill" AutoPlay="True"/>

Y nuestro archivo Xaml debe lucir como el siguiente.

Ya casi terminamos, solamente nos queda agregar el ViewModel para enviar el valor de la propiedad IdYouTube que estamos bindeando en nuestro VideoPlayer, para eso, crearemos un archivo C# dentro de la carpeta ViewModels con el nombre similar al de nuestro Xaml pero con terminacion ViewModel, el mio quedara como YouTubeVideoViewModel.cs (Un poco largo 😅), recordando que tenemos que hacer la clase publica, vamos a agregar el siguiente código.

Aquí agregue el Id de mi ultimo video publicado en mi canal de YouTube, mas adelante les enseño como buscar el Id del video.

Ahora vamos al constructor de la clase “Code-Behind File” de nuestra vista y vamos a pasarle nuestro ViewModel a la propiedad BindingContext, de la siguiente manera.

Para finalizar, solo nos queda hacer que nuestra app inicie con nuestra nueva vista, tan solo reemplazamos el codigo que esta en el contructor de clase “Code-Behind File” del archivo App, con el siguiente.

MainPage = new YouTubeVideo();

Asi quedaria nuestra app, obviamente la resolución del video no es la adecuada, ya que necesita que nuestro dispositivo este de manera horizontal y para eso hay que manejar las propiedades de orientación del dispositivo, habiendo hecho esto, ya tendremos nuestro reproductor listo.

Cuando abrimos un video en youtube, solo tenemos que ir a nuestra barra de navegación y el código que se encuentra luego de v=, es el Id de nuestro video.

Esto ha sido todo por hoy, espero les haya gustado el post, favor compartir y dejar comentarios si les gusta.

8,721 thoughts to “Reproducir Videos de YouTube con Octane Video: Usando MVVM”

  1. You actually make it seem so easy together with your presentation however I in finding this topic to be actually one thing which I think I would by no
    means understand. It kind of feels too complicated and extremely huge for me.

    I’m looking forward on your subsequent submit, I’ll try
    to get the hang of it!

  2. Having read this We believed it seemed to be very enlightening.
    My partner and i appreciate you shelling out some time plus energy to set this content together.
    We again find myself personally spending a great deal of time each reading and efforts.

    But so just what, it was still worth it!

    다운로드사이트

  3. Excellent blog! Do you have any tips and hints for aspiring
    writers? I’m hoping to start my own site soon but I’m a little lost
    on everything. Would you propose starting with a free platform like WordPress or go
    for a paid option? There are so many choices out there that
    I’m completely confused .. Any ideas? Cheers!

  4. Pretty element of content. I just stumbled upon your site and in accession capital
    to assert that I acquire in fact enjoyed account your weblog posts.
    Anyway I will be subscribing in your feeds or even I achievement you get entry
    to persistently rapidly.

  5. Hi, I think your website might be having browser compatibility issues.

    When I look at your blog site in Firefox, it looks fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up!
    Other then that, awesome blog!

  6. I’d like to thank you for the efforts you have put in penning this site.
    I am hoping to check out the same high-grade blog
    posts by you later on as well. In fact, your creative writing abilities has encouraged me
    to get my own website now 😉

  7. This is genuinely interesting, You are the very skilled doodlekit.
    I have became a member of your feed in addition to look forward to trying to find more of the wonderful post.
    Furthermore, I? ve discussed your website within my great example of such!

    먹튀검증

  8. Anya lay on her bed, staring at the ceiling of her moderately-sized dorm room. Her digital alarm clocks LCD display burned a crisp 4:05 AM in the darkness. In two hours and a half she would have to go to class. Her music player was still operating, singing out Pink Floyds later, more ambient sounds. In her head, she went over all the homework she had and every project due withing the next three weeks. Everything was according to schedule. She continued to stare, thinking about how she would make the most of the first weekend her roommate, Tara, was gone.
    https://www.tumblr.com/blog/view/arthur324017668

  9. whoah this weblog is magnificent i love reading your articles.
    Keep up the good work! You know, many individuals are looking round for this information, you could
    aid them greatly.

  10. Hello, i read your blog from time to time and i own a similar one and i was just wondering if you get a lot of spam comments?
    If so how do you reduce it, any plugin or anything you can suggest?
    I get so much lately it’s driving me insane so any help
    is very much appreciated.

  11. I tried so hard to remember what had gotten me here.Could it have happened that first night in the movie theatre?Could it have been when he was fucking me?Could it have been in the theatre today?These are all questions that went through my head.
    The first night we went to the movies turned out to be a most memorable one.My Daddy wanted a blow job.He didnt care who was around, or if they saw, he only wanted to release and release he did.He unzipped his pants and pulled them down away from his cock then took his hand and wrapped it around the back of my neck.
    https://www.tumblr.com/blog/view/quidity5190842

  12. Excellent way of explaining, and fastidious paragraph to get data concerning my presentation focus, which i am going to
    present in school.

  13. Wonderful blog! I found it while surfing around on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo
    News? I’ve been trying for a while but I never seem to get there!
    Cheers

  14. It’s perfect time to make some plans for the future and it is
    time to be happy. I have read this post and if I could I desire to suggest you some interesting things or
    suggestions. Perhaps you can write next articles referring to this article.
    I wish to read even more things about it!

  15. Very great post. I just stumbled upon your weblog and wanted to
    say that I’ve really loved browsing your blog posts.
    After all I’ll be subscribing in your feed and I hope you write once more soon!

  16. God I need a cigarette! I gasped as I collapsed, exhausted, at the top of the small mountain my team had just hiked up in the Lake District.
    Youre supposed to be setting us a good example. Khalid laughed as he flopped down next to me quickly followed by his two schoolmates.
    Fu…To Hell with that! I laughed, I deserve one after a walk like that.
    Still laughing at me puffing and panting the boys whispered something, then Khalid turned to me and asked nervously; Do you really want a smoke?
    https://www.tumblr.com/blog/view/siserary933043

  17. Nice post. I was checking continuously this blog and I am impressed!
    Extremely helpful information particularly the last part
    🙂 I care for such info much. I was looking
    for this certain info for a very long time.

    Thank you and best of luck.

  18. What i do not realize is in reality how you’re now not really much more
    neatly-appreciated than you may be right now.

    You are very intelligent. You realize thus considerably on the subject of this subject, made me for my part consider it from so many various angles.
    Its like women and men are not involved except it’s something to do with Lady gaga!
    Your personal stuffs nice. Always maintain it up!

  19. My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using WordPress on several websites
    for about a year and am worried about switching to another platform.

    I have heard great things about blogengine.net.
    Is there a way I can import all my wordpress
    posts into it? Any help would be greatly appreciated!

  20. I just dont understand what happened? Jax spoke to Tyler as they rode in the front of the bus on their way back to gray rock. They continued the discussion as the boys complained about not getting to see the girls and such. The whole bus ride back was noisy. As the bus pulled into the parking lot and the cadets made their way back to the dorms Jax and Tyler made their way to the armory to check in their weapons. Jax spoke as they walked I know you dont agree with all the behind the scenes stuff he motioned with his fingers as if quoting. But I also have seen how you look and act around that cadet…whats his name…max.
    https://www.tumblr.com/blog/view/icnpiste7109297

  21. This is a story based off of one of my friends and I. He is my best friend in the entire world. I wouldnt trade what we have for anything.
    Adam is my best friend. He is about 63 and is kind of tan considering its always cold here. Hes skinny but has a lot of muscle. He is the star player on our schools basketball and baseball teams. He is so super nice to everyone and is very smart. Hes in a lot of my classes. Hes kind of shy and quiet too.
    https://www.tumblr.com/blog/view/somatognosis3987657

  22. Wonderful beat ! I would like to apprentice at the same time as
    you amend your website, how can i subscribe for a blog web site?
    The account helped me a appropriate deal. I were tiny bit familiar of
    this your broadcast provided brilliant transparent
    concept

  23. Pingback: cialis soft gel
  24. Please let me know if you’re looking for a writer for your
    site. You have some really great articles and I think I would be a good asset.
    If you ever want to take some of the load off, I’d love to write some content
    for your blog in exchange for a link back to mine.
    Please shoot me an e-mail if interested. Cheers!

  25. Pingback: viagra websites
  26. This is really interesting, You might be a very skilled doodlekit.
    I have signed up with your feed and look forward to searching for more of your own wonderful post.
    Furthermore, I? ve shared your website within my social networks!

    슈어맨

  27. [url=https://xtviagra.com/]canada viagra cost[/url] [url=https://viagraedmed.com/]buy viagra super active[/url] [url=https://viagraspecial.com/]sildenafil otc australia[/url] [url=https://viagratrm.com/]order sildenafil from canada[/url] [url=https://slviagra.com/]generic viagra 50[/url] [url=https://viagrajtab.com/]viagra cost[/url] [url=https://viagrax10.com/]buy cheapest generic viagra online[/url] [url=https://ibviagra.com/]price of viagra 100mg uk[/url] [url=https://drugviagra.com/]viagra canadian pharmacy paypal[/url] [url=http://ivermectincov.com/]stromectol usa[/url]

  28. I think this is one of the most important info for me. And i’m glad reading your article. But should remark on few general things, The website style is great, the articles is really excellent : D. Good job, cheers

  29. I love your blog.. very nice colors & theme. Did you make this website yourself or
    did you hire someone to do it for you? Plz respond
    as I’m looking to construct my own blog and would like to find out where u got this from.

    kudos

  30. Hello there, I do believe your blog might be having internet
    browser compatibility issues. When I take a look at your blog in Safari, it looks fine but when opening
    in IE, it’s got some overlapping issues. I simply wanted to provide you with a quick heads up!

    Apart from that, great website!