How to play song in Android - phonegap [closed]

2019-02-02 15:06发布

问题:

A month ago I started working with phonegap, html5, css3 and jQtouch. I am working on an application and I need to play sound in the application. I have a serious problem with this task. First I've found out that I can play .mp3 files through phonegap using the new Media(...) function. I am not sure about .wav files, can I play those? Second I've found that files must be less than 30 sec, is this so? Third I can't find the right place for my sound files. My project structure is the following:

project
-- src
-- gen
-- assets
-- -- www
-- -- DANCE.mp3
-- -- jqtouch
-- -- -- (some folders and files)
-- -- phonegap.js
-- libs
-- res

I've tried placing the file in 'www' folder and creating a new one called 'audio'. None of this gave me what I wanted. I am using this code for executing the song:

function playStream() {
    mp3file = new Media("DANCE.mp3",
            function() {
                alert("playAudio():Audio Success");
            },
                function(err) {
                    alert(err);
            }
            );
          mp3file.play();
}

I use Android 2.1 Simulator and I've tried 2.2 as well without success. I hope I was clear enough. I am looking forward to hearing from you. Yours, Mihail Velikov

回答1:

PhoneGap for Android lets you store local audio files in two places: android_asset: file name must start with /android_asset/sound.mp3 sdcard: file name is just sound.mp3

If you place your DANCE.mp3 file in your project's assets directory, then you can play it using the path:

mp3file = new Media("/android_asset/DANCE.mp3",
        function() {
            alert("playAudio():Audio Success");
        },
            function(err) {
                alert(err);
        }
        );
      mp3file.play();

(You can read the source for AudioPlayer.java in the Android PhoneGap sources to see how this works.)



回答2:

Can I offer an advice.. If you use the PhoneGap Media player.. You need to remove the file:// from the path.. It doesn not accept a full URI for local files Regards Kim



回答3:

I have found out where was my mistake. The audio file that I want to play was not placed properly, as I thought at first. I had moved it in /sdcard folder and everything was just wonderful! P.S. I use only filename, no folders.



回答4:

why dont you just play the songs using the HTML 5 audio tag? Your view is a webView.. is shouldn't matter, it is simpler and you have more control.