Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

cordova - Play sound on Phonegap app for 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.

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

This is the 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

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

The is the file structure

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

Edit 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.Add the following line to config.xml

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

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>

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

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...