2011-12-27 268 views
2

我已經試過這個小時。必須有一個簡單的解決方案來停止聲音並將其卸載爲as3。as3聲音類卸載聲音

這不是我所有的代碼,但總之我加載了隨機聲音。我需要certian vars以外的功能,所以我可以引用他們與進度條的其他功能。

如何卸載聲音,以便我可以使用相同的名稱加載新的聲音而不會在第二次調用它時發生錯誤?

我在這個測試中有兩個按鈕。播放聲音和停止聲音按鈕。

這裏是我的代碼:

var TheSound:Sound = new Sound(); 
var mySoundChannel:SoundChannel = new SoundChannel(); 

PlayButton.addEventListener(MouseEvent.CLICK, PlaySound); 
StopButton.addEventListener(MouseEvent.CLICK, Stopsound); 

function PlaySound(e:MouseEvent) 
     { 
     TheSound.load(new URLRequest("http://www.MyWebsite.com/Noel.mp3")); 
     mySoundChannel = TheSound.play(0); 
     } 

function StopSound(e:MouseEvent) 
     { 
     delete TheSound; 
     } 

以下是錯誤我得到:

Error: Error #2037: Functions called in incorrect sequence, or earlier call was unsuccessful. 
    at flash.media::Sound/_load() 
    at flash.media::Sound/load() 
    at Untitled_fla::MainTimeline/PlaySound()[Untitled_fla.MainTimeline::frame1:21] 

UPDATE ....我試過回採的聲音,然後賣掉,如下

mySoundChannel.stop(); 
TheSound.close(); 

但現在我得到這個錯誤:

Error: Error #2029: This URLStream object does not have a stream opened. 
    at flash.media::Sound/close() 
    at Untitled_fla::MainTimeline/shut1()[Untitled_fla.MainTimeline::frame1:35] 

我相信我更接近。非常感謝您的幫助。

回答

3

爲了阻止播放聲音,你首先要告訴SoundChannel實例來阻止像這樣:

mySoundChannel.stop(); 

一旦你這樣做,你可以通過調用附近的聲音實例所使用的流像這樣的關閉方法:

TheSound.close(); 

此外,delete關鍵字很少在AS3使用,你不應該它,而一些方法試圖訪問要刪除的變量。如果您想要處理當前分配給您的TheSound變量的實例,則應將其值設置爲null。通過這種方式,閃存將正確地垃圾收集舊的Sound實例,該實例在找到合適的時間時不再使用。

+0

哎感謝您的快速幫助。好吧,我試過你的代碼,但我得到一個新的錯誤。我把它貼在上面。 – 2011-12-27 03:59:20

+0

我相信它應該沒問題,如果你只是刪除關閉流的部分。 – joelrobichaud 2011-12-27 04:15:23

+0

好吧,它停止流,但是當我點擊重新加載它時,它得到上面提到的第一個錯誤 「以不正確的順序調用函數,或者更早的調用不成功。」 – 2011-12-27 04:17:25

1

您可以初始化該函數以外的變量,但每次調用該函數時將其定義爲新的Sound對象。這樣它就具有全局範圍,並且您可以隨時加載新的URL。

var TheSound:Sound; 
var mySoundChannel:SoundChannel = new SoundChannel(); 

PlayButton.addEventListener(MouseEvent.CLICK, PlaySound); 
StopButton.addEventListener(MouseEvent.CLICK, StopSound); 

function PlaySound(e:MouseEvent) 
     { 
     TheSound = new Sound(); 
     TheSound.load(new URLRequest("http://www.MyWebsite.com/Noel.mp3")); 
     mySoundChannel = TheSound.play(0); 
     } 

function StopSound(e:MouseEvent) 
     { 
     mySoundChannel.stop(); 
     TheSound.close() 
     }