在flex中播放MP3文件时可以使用flash.media.Sound类和flash.media.SoundChannel。在调用Sound类的play方法时会返回一个SoundChannel对象,在SoundChannel类中提供了存取的方法和属性控制左右声道声音音量的平衡,还有暂停和恢复一个特定声音的方法。
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> <s:layout> <s:BasicLayout/> </s:layout> <fx:Script> <!--[CDATA[ private var _sound:Sound; private var _channel:SoundChannel; private var req:URLRequest = new URLRequest("assets/music/pianai.mp3"); // [Embed(source="assets/music/pianai.mp3")] // private var pianai:Class; private var position:Number = 0; private function playMp3():void{ _sound = new Sound(); _sound.load(req); _channel.addEventListener(Event.SOUND_COMPLETE, playAgain); _channel = _sound.play(position); } private function pauseMp3():void{ position = _channel.position; _channel.stop(); } private function stopMp3():void{ position = 0; _channel.stop(); } private function playAgain():void{ } ]]--> </fx:Script> <fx:Declarations> <!-- 将非可视元素(例如服务、值对象)放在此处 --> </fx:Declarations> <s:Button x="200" y="101" label="播放" click="playMp3()"/> <s:Button x="320" y="101" label="暂停" click="pauseMp3()"/> <s:Button x="420" y="101" label="停止" click="stopMp3()"/> </s:Application>