首页 > 解决方案 > cefsharp 无法通过 javascript 播放音频

问题描述

我正在用 C# 编写一个使用 CefSharp 的字典程序。加载字典页面(即[Longman-love][1])时,我希望它可以自动播放其发音(通过使用JavaScript单击发音图标)。以下是相关代码: C#部分:

    browser.FrameLoadEnd += (sender, args) =>
    {
        //Wait for the MainFrame to finish loading
        if (args.Frame.IsMain)
        {

                browser.ExecuteScriptAsync("document.getElementsByClassName('amefile')[0].click();");

        }
    };

JavaScript 部分(我从网上复制了它并添加了一些用于调试程序的“警报”):

$(document).ready(function(){
var audio = null;

$(".speaker").click(function(){
    alert('x');
    var src_mp3 = $(this).attr("data-src-mp3");

    if (supportAudioHtml5())
        playHtml5(src_mp3);
    else if (supportAudioFlash())
        playFlash(src_mp3);
    else
        playRaw(src_mp3);

});

function supportAudioHtml5(){
    var audioTag  = document.createElement('audio');
    try {
        return ( !!(audioTag.canPlayType)
            && (audioTag.canPlayType("audio/mpeg") != "no" && audioTag.canPlayType("audio/mpeg") != "" ) );
    } catch(e){
        return false;
    }
}

function supportAudioFlash() {
    var flashinstalled = 0;
    var flashversion = 0;
    if (navigator.plugins && navigator.plugins.length){
        x = navigator.plugins["Shockwave Flash"];
        if (x){
            flashinstalled = 2;
            if (x.description) {
                y = x.description;
                flashversion = y.charAt(y.indexOf('.')-1);
            }
        } else {
            flashinstalled = 1;
        }
        if (navigator.plugins["Shockwave Flash 2.0"]){
            flashinstalled = 2;
            flashversion = 2;
        }
    } else if (navigator.mimeTypes && navigator.mimeTypes.length){
        x = navigator.mimeTypes['application/x-shockwave-flash'];
        if (x && x.enabledPlugin)
            flashinstalled = 2;
        else
            flashinstalled = 1;
    } else {
        for(var i=7; i>0; i--){
            flashVersion = 0;
            try{
                var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
                flashVersion = i;
                return (flashVersion > 0);
            } catch(e){}
        }
    }
    return (flashinstalled > 0);
}

function playHtml5(src_mp3) {
    alert('html5');
    if(audio != null){

        if(!audio.ended){
            audio.pause();
            if(audio.currentTime > 0) audio.currentTime = 0;
        }
    }

    //use appropriate source
    audio = new Audio("");
    if (audio.canPlayType("audio/mpeg") != "no" && audio.canPlayType("audio/mpeg") != "")
        audio = new Audio(src_mp3);

    //play
    audio.addEventListener("error", function(e){alert("Apologies, the sound is not available.");});
    alert('will play');
    audio.play();
}

显示了最后一个警告语句alert('will play'); ,但我什么也听不见。但是,当我直接在 CefSharp 浏览器中单击音频图标时,它可以播放发音。我该如何解决这个问题?我不是以英语为母语的人,希望你能理解我。非常感谢![1]:https ://www.ldoceonline.com/dictionary/love

标签: javascriptc#cefsharp

解决方案


出现此问题是因为Google 更改了音频和视频的自动播放策略。您可以通过添加命令行标志来激活自动播放--autoplay-policy=no-user-gesture-required。就我而言:

 public BrowserForm()
        {

            InitializeComponent();
            var settings = new CefSettings();
            settings.CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache");
            settings.CefCommandLineArgs.Add("enable-media-stream", "1"); 
            settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required";//Add this statement solve the problem
            Cef.Initialize(settings); 
            //some other statements
         }

如果有人碰巧在未来遇到同样的问题,我希望这会对你有所帮助!

这是一个相关的话题


推荐阅读