android - html5 音频元素用 jquery 返回 src

标签 android html cordova

我正在将一些 HTML5 转换为适用于 Android。 Android 不支持该元素,因此 play 方法不起作用。

我正在使用 PhoneGap 的媒体元素,它可以播放音频。我想要的是一种找到音频标签的第一个来源,然后将其用于媒体播放的方法,但这似乎不起作用。

function playSound(whatToPlay) {
    // removed since <audio does not work
    // var snd = document.getElementById(whatToPlay);
    // snd.play();

    toPlaySrc = $("#"+whatToPlay+":first-child").eq(0).attr("src");
    // next I will have to deal with /android_asset and my current partial path
    myMedia = new Media("/android_asset/"+toPlaySrc, onSuccess,onError);
    if (myMedia)
        myMedia.play();        
}
playSound("clockticking");

这是我的音频元素。

<audio id="clockticking" preload="auto" autobuffer onEnded="instructionFinsihed()">
  <source src="../sound/tictoc.mp3" type="audio/mp3" />
  <source src="../sound/tictoc.ogg" type="audio/ogg" />
</audio>

我有很多现有的音频元素,所以一个通用的解决方案真的很重要,我不能,例如只向所有 mp3 元素添加 id 标签并解决它。

最佳答案

好的,我正在为 Android WebView 编写一些猴子补丁代码,您可以在我的 corinthian github project 上看到进度.与此同时,你想要做的是设置一个 on deviceready 监听器:

document.addEventListener("deviceready", monkeypunch, true);

创建一个数组来保存媒体对象:

mediaObjs = [];

在 monkeypunch 方法中你会做:

function monkeypunch() {
    var audioclips = document.getElementsByTagName("audio");
    for (var i=0; i < audioclips.length; i++) {
        // Create new Media object.
        var audioSrc = audioclips[i].firstElementChild.src;
        if (audioSrc.indexOf("file:///android_asset") == 0) {
            audioSrc = audioSrc.substring(7);
        }
        mediaObjs[audioSrc] = new Media(audioSrc);
        // Create the HTML
        var newAudio = document.createElement('div');
        var newImg = document.createElement('img');
        newImg.setAttribute('src', 'images/play.png');
        newAudio.appendChild(newImg);
        // Set the onclick listener
        newAudio.addEventListener("click", function() {
            // figure out what image is displayed
            if (newImg.src.indexOf("images/play.png", newImg.src.length - "images/play.png".length) !== -1) {
                newImg.src = "images/pause.png"; 
                mediaObjs[audioSrc].play();               
            } else {
                newImg.src = "images/play.png";
                mediaObjs[audioSrc].pause();                
            }
        });
        // replace the audio tag with out div
        audioclips[i].parentNode.replaceChild(newAudio, audioclips[i]);
    }
}

您可以从我的 github 项目中获取播放/暂停图像。我计划在有更多时间时添加更多功能。

关于android - html5 音频元素用 jquery 返回 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485289/

相关文章:

javascript - Cordova如何旋转相机中的图片

visual-studio - 尝试将 Cordova 应用程序与商店关联时 Visual Studio 崩溃

ios - Cordova Visual Studio 2015 RC 社区 : Remote Device iOS

android - 为什么标记的信息窗口不显示?

android - 如何在切换到另一个选项卡之前更新选项卡布局

html - 比显示 : flex? 更好的居中方式

javascript - 在 mozilla/IE 中淡出无法正常工作

HTML 组织微数据就在关于我们页面或首页也

android - 如何在 android libgdx 上保存和读取整数?

android - 如何在应用程序启动时创建所有 fragment