Music

Interface :: Music >> Music.java

package toxin.schnee.framework;
public interface Music
{
  public abstract void play();
  public abstract void stop();
  public abstract void pause();
  public abstract void setLooping(boolean isLooping);
  public abstract void setVolume(float volume);
  public abstract boolean isPlaying();
  public abstract boolean isStopped();
  public abstract boolean isLooping();
  public abstract void dispose();
}

Concrete :: Music >> MusicImpl.java

package toxin.schnee.framework.impl;

import java.io.IOException;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import toxin.schnee.framework.Music;

public final class MusicImpl implements Music
{
  MediaPlayer mediaPlayer;
  boolean isPrepared = false;

  public MusicImpl(AssetFileDescriptor assetDescriptor){
    mediaPlayer = new MediaPlayer();
    try{
      mediaPlayer.setDataSource(
        assetDescriptor.getFileDescriptor(),
        assetDescriptor.getStartOffset(),
        assetDescriptor.getLength());
      mediaPlayer.prepare();
      isPrepared = true;
      mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
        @Override
        public void onCompletion(MediaPlayer mediaplayer){
          synchronized(this){
            isPrepared = false;
          }
        }
      });
    }catch(Exception e){
      throw new RuntimeException("Couln't load music");
    }
  }
  @Override
  public void play(){
    if(mediaPlayer.isPlaying())
      return;
    try{
      synchronized(this){
        if(!isPrepared)
          mediaPlayer.prepare();
        mediaPlayer.start();
      }
    }catch(IllegalStateException e){
      e.printStackTrace();
    }catch(IOException e){
      e.printStackTrace();
    }
  }
  @Override
  public void stop(){
    mediaPlayer.stop();
    synchronized(this){
     isPrepared = false;
    }
  }
  @Override
  public void pause(){
    if(mediaPlayer.isPlaying())
      mediaPlayer.pause();
  }
  @Override
  public void setLooping(boolean isLooping){
    mediaPlayer.setLooping(isLooping);
  }
  @Override
  public void setVolume(float volume){
    mediaPlayer.setVolume(volume, volume);
  }
  @Override
  public boolean isPlaying(){
    return mediaPlayer.isPlaying();
  }
  @Override
  public boolean isStopped(){
    return !isPrepared;
  }
  @Override
  public boolean isLooping(){
    return mediaPlayer.isLooping();
  }
  @Override
  public void dispose(){
    if(mediaPlayer.isPlaying())
      mediaPlayer.stop();
    mediaPlayer.release();
  }
}
Remove all ads