Avg. Rating 3.3

Problem

Here is a simple method of how to embed an mp3 file into an external stylesheet and have it play in your application

Solution

Using the StyleManager.getStyleDeclaration command we can play mp3 sounds from stylesheets.

Detailed explanation

I have an application which allows users to choose a theme to use. Themes generally have color, image and font differences so using external stylesheets to change themes at runtime was an obvious option. As well I wanted to add sound differences to each theme and came up with a way to bundle this in with the css.

The solution only describes how to embed the mp3 sound file into the css and pull it out at runtime. It does not contain information on how to dynamically change swf css files at runtime. Also note, for the purposes of simplicity, the css files in this demo are not compiled into swf files.

The solution has the following files:

src/soundTest.mxml  - This is the main app file

src/assets/alarm.mp3  - the sound file to play

src/css/main.css  - The stylesheet that contains the sound information

 

main.css:

MySound{
  url: Embed(source='assets/alarm.mp3');
}

This creates a MySound class declaration in the css file and embeds the mp3 file in the url style

Now the soundText.mxml file


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  <mx:Script>
    <![CDATA[

      // This is the function which plays the sound	
      private function playEmbeddedSound():void{
      	// create a CSSStyleDeclaration object which uses the
      	// StyleManager.getStyleDeclaration to get the class 
      	// information from the current application css rules 
        var soundCSSClassDec:CSSStyleDeclaration = StyleManager.getStyleDeclaration("MySound");
        
        // create the MySoundClass object using the CSSStyleDeclaration.getStyle
        // method to retrieve the embedded source of the mp3 file
        var MySoundClass:Class = (soundCSSClassDec.getStyle("url")) as Class;
        var myEmbeddedSound:Sound = new MySoundClass() as Sound;			
        myEmbeddedSound.play();						
      }	
      		
    ]]>
  </mx:Script>

  <!-- add a button to play the sound -->
  <mx:Button click="playEmbeddedSound()" label="Play" />	
  
  <!-- add the stylesheet to the application -->
  <mx:Style source="css/main.css" />
</mx:Application>

When you click the play button it retrieves the mp3 information from the css file and plays it. You can use this method to store your mp3 sounds in css files so you can change sounds based on different themes

Report abuse

Related recipes