问题
I am developing an application with the Ionic Framework and searching for a (very) simple way to play a sound every time a div is clicked. Something similar to this:
<div ng-click="sound()"></div>
$scope.sound = function () {
//sound play once here
}
If the solution could be in angularjs that would be great, but any help would be greatly appreciated.
回答1:
$scope.sound=function(){
var audio = new Audio('audio_file.mp3');
audio.play();
}
回答2:
I don't understand why people recommend the vanilla/ng audio methods. This is Ionic Framework, and in order for this to be compatible on all devices (iOS, Android, Windows Phone etc) it's best to stick to Cordova.
Use the Cordova Media plugin (make sure to have ngCordova
installed and included in your index.html file, as well as defined as a dependency). Inject $cordovaMedia
to the controller/service.
In your controller:
$scope.myMedia = $cordovaMedia.newMedia('audio/song.mp3'); // Must be relative to index.html to work properly on Android
In your view:
<button class="button button-positive" ng-click="myMedia.play()">
Play sound!
</button>
<button class="button button-assertive" ng-click="myMedia.stop()">
Stop sound!
</button>
来源:https://stackoverflow.com/questions/36877446/how-to-play-a-simple-sound-clip-like-a-button-click-when-a-div-is-clicked