Видео недоступно при попытке воспроизвести встроенный URL-адрес YouTube (Xamrin. Android) - PullRequest
0 голосов
/ 09 апреля 2020

Я использую Xamarin Android для разработки приложения для предложений песен, и я использую встроенный URL-адрес YouTube, и я пытаюсь понять, почему некоторые видео воспроизводятся нормально, а другие показывают ошибку и не воспроизводятся совсем. Ошибка «Видео недоступно». Я нашел решение, которое говорит о загрузке html на сервер, но я не могу загрузить его, потому что я меняю видео динамически

Спасибо.

    protected async override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Window.RequestFeature(Android.Views.WindowFeatures.NoTitle);
        SetContentView(Resource.Layout.songSuggestion_layout);
        SetViews();
        categories = new Categories();
        songs = new Songs();
        songSuggsted = new Songs();
        playlist = new Playlist();

        await SetListSongsOfSuggestion();



        var metrics = Resources.DisplayMetrics;
        //fix video screen height and width
        //intDisplayWidth = (FnConvertPixelsToDp(metrics.WidthPixels) + 200);
        //intDisplayHeight = (FnConvertPixelsToDp(metrics.HeightPixels)) / (2);

        intDisplayHeight = 500;
        intDisplayWidth = 1000;
        PlayInWebView();



    }



    public void PlayInWebView()
    {
         string strUrl = songSuggsted[position].UrlSong;

      //  string strUrl= "https://www.youtube.com/watch?v=u_VsvZmIWxY";
        string id = FnGetVideoID(strUrl);
        if (!string.IsNullOrEmpty(id))
        {
            strUrl = string.Format("http://youtube.com/embed/{0}", id);
        }
        else
        {
            Toast.MakeText(this, "Video url is not in correct format", ToastLength.Long).Show();
            return;
        }
        string html = @"<html><body><iframe width=""videoWidth"" height=""videoHeight"" src=""strUrl""></iframe></body></html>";
        var myWebView = (WebView)FindViewById(Resource.Id.videoView);
        var settings = myWebView.Settings;
        settings.JavaScriptEnabled = true;
        settings.UseWideViewPort = true;
        settings.LoadWithOverviewMode = true;
        settings.JavaScriptCanOpenWindowsAutomatically = true;
        settings.DomStorageEnabled = true;
        settings.SetRenderPriority(WebSettings.RenderPriority.High);
        settings.BuiltInZoomControls = false;

        settings.JavaScriptCanOpenWindowsAutomatically = true;
        myWebView.SetWebChromeClient(new WebChromeClient());
        settings.AllowFileAccess = true;
        settings.SetPluginState(WebSettings.PluginState.On);
        string strYouTubeURL = html.Replace("videoWidth", intDisplayWidth.ToString()).Replace("videoHeight", intDisplayHeight.ToString()).Replace("strUrl", strUrl);

        myWebView.LoadDataWithBaseURL(null, strYouTubeURL, "text/html", "UTF-8", null);

    }


    static string FnGetVideoID(string strVideoURL)
    {
        const string regExpPattern = @"youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)";
        //for Vimeo: vimeo\.com/(?:.*#|.*/videos/)?([0-9]+)
        var regEx = new Regex(regExpPattern);
        var match = regEx.Match(strVideoURL);
        return match.Success ? match.Groups[1].Value : null;
    }



    int FnConvertPixelsToDp(float pixelValue)
    {
        var dp = (int)((pixelValue) / Resources.DisplayMetrics.Density);
        return dp;
    }

1 Ответ

0 голосов
/ 23 апреля 2020

Вы можете попробовать следующий код:

Создать веб-просмотр в android макете.

Xaml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.webkit.WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

Код сзади:

 var myWebView = FindViewById<WebView>(Resource.Id.webView1);
        WebSettings setting = myWebView.Settings;
        setting.JavaScriptEnabled = true;
        myWebView.SetWebChromeClient(new WebChromeClient());
        myWebView.LoadUrl("https://www.youtube.com/watch?v=6hzrDeceEKc");

enter image description here

...