简体   繁体   中英

Ionic/Cordova app plays sound in emulator but not on Android device

I'm new to Ionic and Cordova, so I'm sure I'm missing something basic, but my problem is a packaged APK does not play sounds on an Android device. I can get the sound to play in the Ripple emulator just fine with the following code:

.controller('MainCtrl', ['$scope', function ($scope) {
        $scope.playStartBell = function () {
            var media = new Media('media/startBell.mp3', function () {
                console.log('good');
            }, function (err) {
                console.log('bad: ', err);
            });
            media.play();
        },
            $scope.playStopBell = function () {
            var media = new Media('media/stopBell.mp3', function () {
                console.log('good');
            }, function (err) {
                console.log('bad: ', err);
            });
            media.play();
        }
    }])

I've used Cordova to install the media plugin: $cordova plugin add org.apache.cordova.media

According to this SO post , a value needs to be added to the config.xml, but I'm not sure how to do it properly for Ionic/Cordova.

Turns out that you have specify path starting with the /android_asset/www prefix like so:

/android_asset/www/

So changing my code to the following worked. Note you'll want to detect what device you're running on to determine the appropriate location.

.controller('MainCtrl', ['$scope', function ($scope) {
        ///android_asset/www/
        $scope.playStartBell = function () {
            var media = new Media('/android_asset/www/media/startBell.mp3', function () {
                console.log('good');
            }, function (err) {
                console.log('bad: ', err);
            });
            media.play();
        },
            $scope.playStopBell = function () {
            var media = new Media('/android_asset/www/media/stopBell.mp3', function () {
                console.log('good');
            }, function (err) {
                console.log('bad: ', err);
            });
            media.play();
        }
    }])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM