Criando MP3 Player com Actionscript



Neste tutorial você vai aprender a criar seu próprio Ipod usando ActionScript. Nós iremos carregar os arquivos de música a partir de um arquivo XML, pegar todas as músicas do artista e álbum e carregar em nosso arquivo (.fla). Nós não vamos entrar em detalhe sobre o arquivo XML, neste tutorial, mas iremos falar de XML com mais detalhes em outros tutoriais.

>Prévia

Baixar Arquivo(.fla)

Recomendo você olhar para o “arquivo terminado” como não dei uma explicação profunda de XML e ActionScript 3 é legal você olhar antes.

Atenção! Eu não adcionei nenhuma música na pasta do Ipod para que você possa aprender como adcionar novas músicas.

Em primeiro lugar olhe o arquivo (.fla) que você baixou, ele é o nosso arquivo inicial. Sobre o Ipod temos os botões “play”, “pause” e “back” eles retornam os nomes “pause_btn exemplo”, “play_btn, prev_btn” e “next_btn” respectivamente. A primeira coisa que nós vamos fazer é criar algumas caixas de texto dinâmicas para carregar o nome das músicas adcionadas

01. Texto Dinâmico

Selecione a ferramenta “Text” agora vá no painel “Properties” e selecione “Dynamic Text” agora crie três caixas de texto na tela do Ipode colocando nome em cada uma delas como “artistTXT”, albumTXT e songTXT.



02.Adicionar o ActionScript

Vá para a camada ações abra o painel do Actionscript e cole o código abaixo.

var getMusic:URLRequest;
var music:Sound = new Sound();
var soundChannel:SoundChannel;
var currentSound:Sound = music;
var pos:Number;
var songPlaying:Boolean = false;
var xml:XML;
var songlist:XMLList;
var currentIndex:Number = 0;

03. Preloader

Iremos criar um simples “preloader” para carregar o nosso conteúdo.

function loadProgress(event:ProgressEvent):void {
var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
percentLoaded = Math.round(percentLoaded * 100);
if(percentLoaded > 20){
trace(”loading”);
} else{
}
}

function completeHandler(event):void {
trace(”DONE”);
}

04. Load no XML

Aquí estamos com nosso “Load” XML ,agora vamos criar uma função que será executada quando o nosso loader concluir carregamento.

var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, whenLoaded);
loader.load(new URLRequest(”songs.xml”));

function whenLoaded(e:Event):void
{
xml = new XML(e.target.data);
songlist = xml.song;
getMusic = new URLRequest(songlist[0].url);
music.load(getMusic);
soundChannel = music.play();
songTXT.text = songlist[0].title;
artistTXT.text = songlist[0].artist;
albumTXT.text = songlist[0].album;

soundChannel.addEventListener(Event.SOUND_COMPLETE, nextSong);
}

05. Adicionar evento ouvintes para botões.

Agora vamos adicionar alguns eventos para os nossos botões do mouse sobre o iPod e dar-lhes algumas funções.

next_btn.addEventListener(MouseEvent.CLICK, nextSong);
prev_btn.addEventListener(MouseEvent.CLICK, prevSong);
pause_btn.addEventListener(MouseEvent.CLICK,pauseSong);
function nextSong(e:Event):void
{
if (currentIndex < (songlist.length() - 1))
{
currentIndex++;
}
else
{
currentIndex = 0;
}
var nextReq:URLRequest = new URLRequest(songlist[currentIndex].url);
var nextTitle:Sound = new Sound(nextReq);
soundChannel.stop();
songTXT.text = songlist[currentIndex].title;
artistTXT.text = songlist[currentIndex].artist;
albumTXT.text = songlist[currentIndex].album;
soundChannel = nextTitle.play();
songPlaying = true;
currentSound = nextTitle;
soundChannel.addEventListener(Event.SOUND_COMPLETE, nextSong);
}
function prevSong(e:Event):void
{
if (currentIndex > 0)
{
currentIndex–;
}
else
{
currentIndex = songlist.length() - 1;
}
var nextReq:URLRequest = new URLRequest(songlist[currentIndex].url);
var prevTitle:Sound = new Sound(nextReq);
soundChannel.stop();
songTXT.text = songlist[currentIndex].title;
artistTXT.text = songlist[currentIndex].artist;
albumTXT.text = songlist[currentIndex].album;
soundChannel = prevTitle.play();
songPlaying = true;
currentSound = prevTitle;
soundChannel.addEventListener(Event.SOUND_COMPLETE, nextSong);
}
function pauseSong(e:Event):void
{
pos = soundChannel.position;
soundChannel.stop();
songPlaying = false;
play_btn.addEventListener(MouseEvent.CLICK,playSong);
}
function playSong(e:Event):void
{
if(songPlaying == false)
{
soundChannel = currentSound.play(pos);
soundChannel.addEventListener(Event.SOUND_COMPLETE, nextSong);
songPlaying = true;
play_btn.removeEventListener(MouseEvent.CLICK,playSong);
}
}

Chegamos ao fim, agora só basta testar o seu Ipod.

Tutorial retirado de http://www.flashessential.com
Abraço, até a próxima.

7 comentários:

Anônimo disse...

Oi. Olhe o source , tem alguns bugs.

Anônimo disse...

Colega, é AS3, o código está funcionando.

Israel C. Araujo disse...

gostaria de criar um mp3 player com um arquivo externo .as.como faço?

L3th0r disse...

Gostaria de colocar um botão de volume como faria?

Anônimo disse...

Obrigada, colega! Funcionou perfeitamente!

claudio disse...

Gostaria de saber como adicionar na action o codigo de um botão stop para parar a musica do mp3 player.

Aguardo retorno
Muito obrigado

Eduardo Favarin disse...

Não to conseguindo baixar o arquivo mp3.rar. Poderia re-up ele?