在适用于 Android 的 Phonegap 应用程序上播放声音 [英] Play sound on Phonegap app for Android

查看:27
本文介绍了在适用于 Android 的 Phonegap 应用程序上播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 文件,但我仍然不知道如何修复它.

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

这是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>

这是Javascript

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

这是文件结构

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

编辑 1

我试过了

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

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

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

我试过了

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

这行得通,但我需要播放本地文件

This worked, but I need to get local files playing

推荐答案

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

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.

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

1.Add the following line to config.xml

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

2.替换 index.html 中的行

2.Replace the lines in index.html

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

用这些行

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

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

3.Add the following function to 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();
}

这篇关于在适用于 Android 的 Phonegap 应用程序上播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆