Android PhoneGap 应用程序中未播放 HTML5 音频(可以使用媒体吗?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21638741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:51:59  来源:igfitidea点击:

HTML5 audio not playing in PhoneGap App (Possible to use Media?)

androidhtmlcordovaphonegap-build

提问by BR89

Working on a basic sound board for a trip abroad. Set up everything to work fine in Browsers but wanted to use PhoneGap Build/GitHub to make it downloadable as cell service won't be available.

为出国旅行制作基本的音板。设置一切以在浏览器中正常工作,但想使用 PhoneGap Build/GitHub 使其可下载,因为手机服务将不可用。

Everything working great in desktop browser however once its installed on Android, the mp3 files don't play. I've read some others posts on here about the inconsistencies of mp3s on PhoneGap. Some suggestions offered using "media" in place of . I'm not sure how to swap that out in place of the code I have now. Seems to use javascript instead of just html. http://docs.phonegap.com/en/2.0.0/cordova_media_media.md.html#MediaSample of what I'm using:

在桌面浏览器中一切正常,但是一旦安装在 Android 上,mp3 文件就无法播放。我在这里阅读了其他一些关于 PhoneGap 上 mp3 不一致的帖子。使用“媒体”代替 . 我不确定如何将其替换为我现在拥有的代码。似乎使用 javascript 而不仅仅是 html。http://docs.phonegap.com/en/2.0.0/cordova_media_media.md.html#Media我正在使用的示例:

<audio id="yes" src="audio/basic/yes.mp3"></audio>
<audio id="no" src="audio/basic/no.mp3"></audio>

<button class="button" onclick="document.getElementById('yes').play()">Yes</button>
<button class="button" onclick="document.getElementById('no').play()">No</button>

Works great in browser, but not on Android. Can anyone offer a starting point to correct the audio?

在浏览器中运行良好,但不适用于 Android。谁能提供一个起点来纠正音频?

Thanks -BR

谢谢-BR

EDIT 2-9-14

编辑 2-9-14

No luck so far. The media plugin is showing as correctly installed and cordova.js is included. Here's what I've tried.

到目前为止没有运气。媒体插件显示为正确安装并且包含了cordova.js。这是我尝试过的。

<!DOCTYPE HTML>
<html>
  <head>
    <title>Media Example</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
    // success callback
    function() {
        console.log("playAudio():Audio Success");
    },
    // error callback
    function(err) {
        console.log("playAudio():Audio Error: "+err);
});

// Play audio
my_media.play();
}
    </script>
  </head>
  <body>

  <a href="#" class="button" onclick="playAudio('/android_asset/www/audio/basic/yes.mp3');">Yes</a>

  </body>
</html>

Also tried to work with the code you suggested

还尝试使用您建议的代码

<!DOCTYPE html>
<html>
<head>

<title>Transactions</title>

<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript">
var my_media = null;
var mediaTimer = null;
function playAudio(src) {
 // Create Media object from src
 my_media = new Media(src, onSuccess, onError);
 // Play audio
 my_media.play();
 // Update my_media position every second
 if (mediaTimer == null) {
    mediaTimer = setInterval(function () {
            // get my_media position
            my_media.getCurrentPosition(
                // success callback
                function (position) {
                if (position > -1) {
                    setAudioPosition((position) + " sec");
                }
            },
            // error callback
            function (e) {
                console.log("Error getting pos=" + e);
                setAudioPosition("Error: " + e);
            });
        }, 1000);
    }
}
// onSuccess Callback
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
function onError(error) {
 alert('code: ' + error.code + '\n' +
    'message: ' + error.message + '\n');
}

</script>


<link rel="stylesheet" type="text/css" href="style.css">

</head>

<body>



document.addEventListener("deviceready", function () {
$("#Yes").on("click", function () {
    playAudio(audio/basic/yes.mp3);
});
$("#No").on("click", function () {
    playAudio(audio/basic/no.mp3);
});


<button class="button" id="Yes">Yes</button>
<button class="button" id="No">No</button>



</body>

</html>

Edit 2/10/14

编辑 2/10/14

Unfortunately still no such luck. Most recent update below

不幸的是仍然没有这样的运气。最新更新如下

<!DOCTYPE html>
<html> 
<head>

<title>Transactions</title>

<!-- JavaScript -->
<script type="text/javascript" charset="utf-8" src="cordova.js"></script> 
<script type="text/javascript">


document.addEventListener("deviceready", function () {
$("#yes").on("click", function () {
    playAudio(/android_asset/www/audio/basic/yes.mp3);
});
$("#no").on("click", function () {
    playAudio(/android_asset/www/audio/basic/no.mp3);
});
}, false);

    var my_media = null;
var mediaTimer = null;
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// Play audio
my_media.play();
}
// onSuccess Callback
function onSuccess() {
console.log("playAudio():Audio Success");
 }
// onError Callback
function onError(error) {
alert('code: ' + error.code + '\n' +
    'message: ' + error.message + '\n');
 }
</script>

<!-- CSS -->
<link rel="stylesheet" type="text/css" href="style.css">

</head>

<body>




<button class="button" id="yes">Yes</button>
<button class="button" id="no">No</button>



</body>

</html>

回答by John McDonald

I've been banging my head all week, and I finally got Mediato work! There are many gotchas:

我整个星期都在敲我的头,我终于开始Media工作了!有很多问题:

As per Geevan's answer, you do need <script type="text/javascript" src="phonegap.js"></script>on your page.

根据 Geevan 的回答,您确实需要<script type="text/javascript" src="phonegap.js"></script>在您的页面上。

Step 1:

第1步:

You need to use org.apache.cordova.media version 0.2.9 or higher (I'm using 0.2.11). As of this writing, PhoneGap Build only supports up to version 0.2.8. I believe the patch notes for 0.2.9may have resolved my issues.

您需要使用 org.apache.cordova.media 版本 0.2.9 或更高版本(我使用的是 0.2.11)。在撰写本文时,PhoneGap Build 最高仅支持 0.2.8 版本。我相信0.2.9补丁说明可能已经解决了我的问题。

Step 2:

第2步:

The PhoneGap documentation for version 3.0.0 has a typo, be sure you are using at least the 3.3.0 documentation, and make sure that the following is typo-free in your config.xml:

3.0.0 版的 PhoneGap 文档有错字,请确保您至少使用3.3.0 文档,并确保以下内容在您的config.xml:

<feature name="Media">
    <param name="android-package" value="org.apache.cordova.media.AudioHandler" />
</feature>

(the word "media" in "org.apache.cordova.media.AudioHandler" was missing in the 3.0.0 documentation)

(3.0.0 文档中缺少“org.apache.cordova.media.AudioHandler”中的“media”一词)

Step 3:

第 3 步:

If you're forced to use the CLI version of PhoneGap (NOT PhoneGap Build) due to the issue described in step 1, be sure you add the required plugins. This is described in the documentation:

如果由于步骤 1 中描述的问题而被迫使用 PhoneGap 的 CLI 版本(不是 PhoneGap Build),请确保添加所需的插件。这在文档中描述:

> cordova plugin add org.apache.cordova.media

And add <gap:plugin name="org.apache.cordova.media" />to your config.xml

并添加<gap:plugin name="org.apache.cordova.media" />到您的config.xml

Step 4:

第四步:

You need to add "/android_asset/www/" to all of your audio file paths. Eg:

您需要将“/android_asset/www/”添加到所有音频文件路径。例如:

new Media('/android_asset/www/' + src);

Step 5:

第 5 步:

Do all audio loading afterthe device is ready. Eg:

在设备准备好执行所有音频加载。例如:

document.addEventListener("deviceready", Game.load);

Once I made these changes, my audio started to work! Good luck!

进行这些更改后,我的音频就开始工作了!祝你好运!

回答by QuickFix

I think you should say "Works great in desktop browser", it is more a matter of support of media in the android default browser than an issue with phonegap.

我认为您应该说“在桌面浏览器中效果很好”,这更多是 android 默认浏览器中媒体支持的问题,而不是 phonegap 的问题。

According to this page, the android browser supports mp3 on some device, and ogg on others. Maybe your issue is that you're trying to use mp3 on a device only supporting ogg for media in the browser?

根据此页面,Android 浏览器在某些设备上支持 mp3,在其他设备上支持 ogg。也许您的问题是您试图在浏览器中仅支持 ogg 媒体的设备上使用 mp3?

Using phonegap media pluginshould solve the problem.

使用phonegap 媒体插件应该可以解决问题。

The full example in the documentation page is quite clear. You just have to copy in your page the playAudio, onSuccessand onErrorfunctions and then call playAudio whenever you want to play a file.

文档页面中的完整示例非常清楚。您只需在页面中复制playAudio,onSuccessonError函数,然后在想要播放文件时调用 playAudio 。

The html of your page could look like this :

您页面的 html 可能如下所示:

<button class="button" id="btnYes">Yes</button>
<button class="button" id="btnNo">No</button> 

and the javasctipt (using jquery):

和 javasctipt(使用 jquery):

document.addEventListener("deviceready", function () {
    $("#btnYes").on("click", function () {
        playAudio(audio/basic/yes.mp3);
    });
    $("#btnNo").on("click", function () {
        playAudio(audio/basic/no.mp3);
    });
}, false);
var my_media = null;
var mediaTimer = null;
function playAudio(src) {
    // Create Media object from src
    my_media = new Media(src, onSuccess, onError);
    // Play audio
    my_media.play();
}
// onSuccess Callback
function onSuccess() {
    console.log("playAudio():Audio Success");
}
// onError Callback
function onError(error) {
    alert('code: ' + error.code + '\n' +
        'message: ' + error.message + '\n');
}

The calls to playAudio could also be in the onclick directly in the html, but I prefered to use jquery to start listening for clicks only once phonegap is ready.

对 playAudio 的调用也可以直接在 html 中的 onclick 中,但我更喜欢使用 jquery 仅在 phonegap 准备好后才开始监听点击。

Don't forget to include cordova.js, and if you're using phonegap 3.x don't forget to install the org.apache.cordova.media plugin

不要忘记包含cordova.js,如果你使用phonegap 3.x 不要忘记安装org.apache.cordova.media 插件

Edit:

编辑:

path audio/basic/yes.mp3assumes that the file is in the audio folder at the root of the sd card.

pathaudio/basic/yes.mp3假定文件位于 SD 卡根目录的音频文件夹中。

use /android_asset/www/audio/basic/yes.mp3if the audio folder is located in the phonegap www folder.

使用/android_asset/www/audio/basic/yes.mp3如果音频文件夹位于PhoneGap的WWW文件夹。

回答by Raony Guimar?es

Uff that was really hard and confusing ... But I finally did it!

Uff 真的很难而且很混乱......但我终于做到了!

Here is exactly what i did:

这正是我所做的:

index.html

索引.html

<audio id="successSound" src="sounds/sayHello.mp3" type="audio/mpeg" ></audio>
<button onclick="playAudio('successSound')">Play successSound local</button>

AndroidManifest.xml

AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

index.js

索引.js

function playAudio(id) {
var audioElement = document.getElementById(id);
var url = audioElement.getAttribute('src');
var my_media = new Media('/android_asset/www/' + url,
        // success callback
         function () { console.log("playAudio():Audio Success"); },
        // error callback
         function (err) { console.log("playAudio():Audio Error: " + err); }
);
       // Play audio
my_media.play();

}

}

plataform/android/res/xml.config

平台/android/res/xml.config

<feature name="Media">
        <param name="android-package" value="org.apache.cordova.media.AudioHandler" />
    </feature>

And it finally works!!! :D uhuuuuu

它终于奏效了!!!:D uhuuuuu

回答by mico

It could be a content security problem, try with this header in your index.html. In my test project, including or excluding it makes or breaks audio playback and reading local files with $.get()or something like that

这可能是内容安全问题,请尝试在 index.html 中使用此标头。在我的测试项目中,包括或排除它使或中断音频播放和读取本地文件$.get()或类似的东西

<meta http-equiv="Content-Security-Policy" content="default-src 'self' http://appvipswi.easwi.it; script-src 'self' 'unsafe-inline'; media-src 'self'">

回答by Leon Chamier

none of the above worked for me. I have to change the file extension. This is whats worked.

以上都不适合我。我必须更改文件扩展名。这就是有效的。

<audio id="a3" controls="controls">
  <source id="s3" src="mp3.audio" type="audio/mp3" />
</audio>

I didnt even have to specify /android_asset/www/

我什至不必指定 /android_asset/www/

回答by AAhad

Its a sound file path issue.

它的声音文件路径问题

instead of /android_asset/www/audio/AudioFile2.mp3

代替 /android_asset/www/audio/AudioFile2.mp3

try

尝试

/android_asset/www/default/audio/AudioFile2.mp3

I see all other settings are correct in your shared code.

我看到您的共享代码中的所有其他设置都是正确的。

回答by Geevan

If you are compiling build in cloud,

如果您在云中编译构建,

Just add following line in your index.html

只需在 index.html 中添加以下行

<script type="text/javascript" src="phonegap.js"></script>

Note:No need to include source phonegap.js, while compiling build phonegap.js will be added.

注意:无需包含源码phonegap.js,编译时会添加phonegap.js。

Also include media plugin in config.xml as:

还包括 config.xml 中的媒体插件:

If platform is Android, If media present in root then Media url must be : /android_asset/www/test.mp3

如果平台是 Android,如果媒体存在于 root 中,则媒体 url 必须是:/android_asset/www/test.mp3