在适用于 Android 的 Phonegap 应用程序上播放声音

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22515699/
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 06:06:34  来源:igfitidea点击:

Play sound on Phonegap app for Android

androidcordova

提问by Mathias F

I try to play an mp3 file. This works if I change the path to the file on my local webserver, but if I run this on an Android device the sound is not played and no error is shown.

我尝试播放 mp3 文件。如果我在本地网络服务器上更改文件的路径,这会起作用,但是如果我在 Android 设备上运行它,则不会播放声音并且不会显示任何错误。

I am pretty shure that the mp3 file is not found, but I still don't know how to fix it.

我很确定没有找到 mp3 文件,但我仍然不知道如何修复它。

This is the Html

这是Html

  <body>

        <audio id="successSound" src="/android_asset/www/sound/successSound.mp3" type="audio/mpeg" ></audio>
           <audio id="errorSound" src="/android_asset/www/sound/errorSound.mp3" type="audio/mpeg" ></audio>
<!-- some more UI -->
  </body>

This is the Javascript

这是Javascript

document.getElementById('errorSound').play();

The is the file structure

文件结构

phonyapp
`-- www
    `-- index.html
        |-- sound
        |   |-- errorSound.mp3
        |   `-- successSound.mp3
        |-- res
        `-- spec

Edit 1

编辑 1

I tried

我试过

<audio id="successSound" src="sound/successSound.mp3" type="audio/mpeg" ></audio>

This worked in chrome on my local webserver but not on Android.

这在我的本地网络服务器上的 chrome 中有效,但在 Android 上无效。

I tried

我试过

<audio id="successSound" src="http://html5multimedia.com/media/sayHello.mp3" type="audio/mpeg" ></audio>

This worked, but I need to get local files playing

这有效,但我需要播放本地文件

回答by Surajit Sarkar

The play method which the HTML5 API provides is useful for playing media files available on the web. Phonegap provides the media plugin to play local media files. I checked out your code and played the sound successfully by making the following changes. Please check at your end.

HTML5 API 提供的播放方法对于播放网络上可用的媒体文件很有用。Phonegap 提供了媒体插件来播放本地媒体文件。我检查了您的代码并通过进行以下更改成功播放了声音。请检查你的最后。

1.Add the following line to config.xml

1.在config.xml中添加以下行

<gap:plugin name="org.apache.cordova.media" />

2.Replace the lines in index.html

2.替换index.html中的行

<button onclick="document.getElementById('successSound').play()">Play successSound local</button>
<button onclick="document.getElementById('errorSound').play()">Play errorSound local</button>

with these lines

用这些线

<button onclick="playAudio('successSound')">Play successSound local</button>
<button onclick="playAudio('errorSound')">Play errorSoundlocal</button>

3.Add the following function to js/index.js

3.在js/index.js中添加如下函数

function playAudio(id) {
    var audioElement = document.getElementById(id);
    var url = audioElement.getAttribute('src');
    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();
}

回答by Praveena

Use this code

使用此代码

  <body>

    <audio id="successSound" src="file:///android_asset/www/sound/successSound.mp3"      type="audio/mpeg" ></audio>
       <audio id="errorSound" src="file///android_asset/www/sound/errorSound.mp3"   type="audio/mpeg" ></audio>
<!-- some more UI -->
 </body>

回答by panpan

I had the same problem and finally got it working, with me the problem lied with the scope of my media variable. I got it working as follows:

我遇到了同样的问题,终于让它工作了,我的问题在于我的媒体变量的范围。我让它工作如下:

(function () {

    "use strict";
     var media;
     document.addEventListener('deviceready', onDeviceReady.bind(this), false);

function onDeviceReady() {
    media = new Media("/android_asset/www/sounds/wat is je wens.mp3", null, function (e) {
    alert('Media Error');
    alert(JSON.stringify(e));
    });

    alert('deviceready')
};
function onStart() {
    media.play();
    alert('yay')

}
};

Essentially I made sure that the scope of my media variable was sort of global by declaring it outside of onDeviceReady, but that Media wasn't called before the deviceready event.

本质上,我通过在 onDeviceReady 之外声明它来确保我的媒体变量的范围是全局的,但是在 deviceready 事件之前没有调用该媒体。

回答by Bugasiso

`` // Audio player
        //
        var my_media = null;
        var mediaTimer = null;
        // Play audio
        //
        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");
        }
function stopAudio() {
            if (my_media) {
                my_media.stop();
            }
            clearInterval(mediaTimer);
            mediaTimer = null;
        }
        // onError Callback
        //
        function onError(error) {
        }
        // Set audio position
        //
        function setAudioPosition(position) {
            document.getElementById('audio_position').innerHTML = position;
        }

回答by Bugasiso

Did you try removing the /android_asset/www/part in your code? Your app acts like a website and it thinks its root is the www folder itself.

您是否尝试删除/android_asset/www/代码中的部分?你的应用程序就像一个网站,它认为它的根是 www 文件夹本身。

Edit: I'll edit comment. Code not showing somehow.

编辑:我会编辑评论。代码没有以某种方式显示。

回答by sschrass

If you are using local files, try to reference them with src="file:///yourpath/sayHello.mp3"

如果您使用的是本地文件,请尝试使用 src="file:///yourpath/sayHello.mp3"