1

我使用以下示例播放 MP3 文件(我不需要/想要“打开”对话框):

<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView">

<fx:Script>
    <![CDATA[
        import flash.media.*;
        [Embed(source="assets/marseljeza.mp3")]

              [Bindable]
        public var sndCls:Class;
        public var snd:Sound = new sndCls() as Sound; 
        public var sndChannel:SoundChannel;

        public function playSound():void {
            sndChannel=snd.play();
        }   
        public function stopSound():void {
            sndChannel.stop();
        }   
    ]]>
</fx:Script>

<s:HGroup>
    <s:Button label="play" click="playSound();"/>
    <s:Button label="stop" click="stopSound();"/>
</s:HGroup>
</s:View>`

点击播放按钮后,MP3文件播放正常,但如果我再次点击播放按钮,歌曲同时从头开始,如果我点击按钮三、四、五或更多,同样如此次。所以我最终得到了同一首歌的更多同时“会话”。我想在第一次单击后禁用 PLAY 按钮,并在单击 STOP 后再次启用相同的按钮。我怎样才能做到这一点?

4

1 回答 1

0

要回答您的具体问题,您可以使用按钮上的 enabled 属性。在您的 playSound() 方法中,执行以下操作::

public function playSound():void {
    sndChannel=snd.play();
    playButton.enabled = false;
}   

请务必向您的 playButton 添加一个 Id:

<s:Button id="playButton" label="play" click="playSound();"/>

您可能需要考虑在 playSound() 方法中添加一个检查,以便在声音已经播放时不播放它。为此,首先创建一个变量:

protected var isPlaying : Boolean = false;

然后像这样调整 playButton() 方法:

public function playSound():void {
   if(!isPlaying){
    sndChannel=snd.play();
    isPlaying = true;
   }
}   

在上述任何一种情况下,您可能都希望将事件侦听器添加到完整事件,以便重新启用按钮或更改 isPlaying 标志。该方法将是这样的:

public function playSound():void {
   if(!isPlaying){
    snd.addEventListener(Event.COMPLETE,onSoundComplete);
    sndChannel=snd.play();
    isPlaying = true;
   }
}   

public function onSoundComplete(event:Event):void{
  isPlaying = false;
  playButton.enabled = true;
  snd.removeEventListener(Event.COMPLETE,onSoundComplete);
}

您还可以从停止声音方法中调用 onSoundComplete 方法:

    public function stopSound():void {
        sndChannel.stop();
        onSoundComplete(new Event());
    }   
于 2012-10-02T20:37:51.047 回答