How to play a simple sound clip (like a button click) when a div is clicked

雨燕双飞 提交于 2020-01-30 06:53:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!