phonegap中播放音频的示例分析

本文讲解"phonegap中播放音频的示例分析",用于解决相关问题。

实例如下:

<!DOCTYPE html> 
<html>
    <head> 
        <meta charset="UTF-8"> 
        <title>Compass Example</title> 
  
        <script type="text/javascript" charset="UTF-8" src="cordova.js"></script> 
        <script type="text/javascript" charset="UTF-8"> 
            document.addEventListener("deviceready", onDeviceReady, false); 
  
            function onDeviceReady() { 
            } 
              
            var my_media=null; 
            var mediaTimer=null; 
              
            function playAudio(src){ 
                my_media=new Media(src,onSuccess,onError); 
                my_media.play(); 
                  
                if(mediaTimer==null){ 
                    mediaTimer=setInterval(function(){ 
                        my_media.getCurrentPosition( 
                            //成功回调 
                            function(position){ 
                            if(position>-1){ 
                                setAudioPosition((position/1000)+"sec"); 
                            } 
                        }, 
                        //错误回调 
                        function (e){ 
                            console.log("Error getting pos="+e); 
                            setAudioPosition("Error: "+e); 
                        } 
                        ); 
                    },1000); 
                } 
            } 
              
            function pauseAudio(){ 
                if(my_media){ 
                    my_media.pause(); 
                } 
            } 
              
            function stopAudio(){ 
                if(my_media){ 
                    my_media.stopAudio(); 
                } 
                clearInterval(mediaTimer); 
                mediaTimer=null; 
            } 
              
            function onSuccess(){ 
                console.log("playAudio():Audio Success"); 
            } 
              
            function setAudioPosition(position){ 
                document.getElementById('audio_position').innerHTML=position; 
            } 
  
            //错误的回调  
            function onError(error) { 
                alert('code:'+error.code+'\n'+'message:'+error.message+'\n'); 
            } 
              
        </script> 
    </head> 
  
    <body> 
        <a href="#" onclick="playAudio('http://example.com/audio.mp3');">Play Audio</a> 
        <a href="#" onclick="pauseAudio();">Pause Playing Audio</a> 
        <a href="#" onclick="stopAudio();">Stop Playing Audio</a> 
        <p id="audio_position"></p> 
    </body> 
  
</html>

关于 "phonegap中播放音频的示例分析" 就介绍到此。希望多多支持编程宝库

本文讲解"phonegap中有哪些常用事件",用于解决相关问题。在任何PhoneGap项目中,首先应该侦听deviceready事件。事件触发表示DOM已经加载和PhoneGapAPI已加载,此时可以检测其 ...