2008-10-11 77 views
4

如何可靠地检查SoundChannel是否仍在播放声音?检查SoundChannel是否正在播放声音

例如,

[Embed(source="song.mp3")] 
var Song: Class; 

var s: Song = new Song(); 
var ch: SoundChannel = s.play(); 

// how to check if ch is playing? 

回答

10

我做了一些研究,我无法找到一个方法来查询任何对象,以确定是否一个声音响起。你将不得不编写一个包装类并且自己管理它。


package 
{ 
    import flash.events.Event; 
    import flash.media.Sound; 
    import flash.media.SoundChannel; 

    public class SoundPlayer 
    { 
     [Embed(source="song.mp3")] 
     private var Song:Class; 

     private var s:Song; 
     private var ch:SoundChannel; 
     private var isSoundPlaying:Boolean; 

     public function SoundPlayer() 
     { 
      s = new Song(); 
      play(); 
     } 

     public function play():void 
     { 
      if(!isPlaying) 
      { 
       ch = s.play(); 
       ch.addEventListener(
        Event.SOUND_COMPLETE, 
        handleSoundComplete); 
       isSoundPlaying = true; 
      } 
     } 

     public function stop():void 
     { 
      if(isPlaying) 
      { 
       ch.stop(); 
       isSoundPlaying = false; 
      } 
     } 

     private function handleSoundComplete(ev:Event):void 
     { 
      isSoundPlaying = false; 
     } 
    } 
} 
0

一个检查,如果声音还在玩,并且不使用任何管理人员,将检查soundChannel.position在两个连续的enterFrame事件侦听器调用,如果不匹配,那么声音仍在播放的方式。

private var oldPosition:Number; 
function onEnterFrame(e:Event):void { 
    var stillPlaying:Boolean; 
    var newPosition=soundChannel.position; 
    if (newPosition-oldPosition>1) stillPlaying=true; else stillPlaying=false; 
    oldPosition=newPosition; 
} 
+0

由于这在技术上是正确的,我不建议任何人实际使用它。 – WORMSS 2013-01-22 13:46:48