Android Open Source - droidengine2d Music Player






From Project

Back to project page droidengine2d.

License

The source code is released under:

Apache License

If you think the Android project droidengine2d listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*   Copyright 2013-2014 Miguel Vicente Linares
 *//  ww  w  . j  a va2s.c o  m
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.miviclin.droidengine2d.audio;

import java.io.IOException;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

import com.miviclin.droidengine2d.resources.AssetsLoader;

/**
 * MusicPlayer can be used to control playback of audio files.
 * 
 * @author Miguel Vicente Linares
 * 
 */
public class MusicPlayer implements OnCompletionListener {

  public static final float MIN_VOLUME = 0.0f;
  public static final float MAX_VOLUME = 1.0f;

  private MediaPlayer player;
  private boolean prepared;
  private boolean loaded;
  private float volume;

  /**
   * Creates a new MusicManager.
   */
  public MusicPlayer() {
    this.player = null;
    this.prepared = false;
    this.loaded = false;
    this.volume = -1.0f;
  }

  @Override
  public void onCompletion(MediaPlayer player) {
    synchronized (this) {
      prepared = false;
    }
  }

  /**
   * Loads music from the specified file and prepares the MediaPlayer for playing it. Looping is enabled by default.
   * 
   * @param context Context.
   * @param path File path.
   */
  public void loadMusic(Context context, String path) {
    loadMusic(context, path, AudioManager.STREAM_MUSIC);
  }

  /**
   * Loads music from the specified file and prepares the MediaPlayer for playing it. Looping is enabled by default.
   * 
   * @param context Context.
   * @param path File path.
   * @param streamType The type of the audio stream. Use {@link AudioManager#STREAM_ALARM},
   *            {@link AudioManager#STREAM_DTMF}, {@link AudioManager#STREAM_MUSIC},
   *            {@link AudioManager#STREAM_NOTIFICATION}, {@link AudioManager#STREAM_RING},
   *            {@link AudioManager#STREAM_SYSTEM}, or {@link AudioManager#STREAM_VOICE_CALL}.
   */
  public void loadMusic(Context context, String path, int streamType) {
    if (path.matches("[a-z]+://.+")) {
      loadExternalMusic(path, streamType);
    } else {
      loadMusicFromAssets(context, path, streamType);
    }
  }

  /**
   * Loads music from the specified external file and prepares the MediaPlayer for playing it. Looping is enabled by
   * default.
   * 
   * @param path External file path.
   */
  public void loadExternalMusic(String path) {
    loadExternalMusic(path, AudioManager.STREAM_MUSIC);
  }

  /**
   * Loads music from the specified external file and prepares the MediaPlayer for playing it. Looping is enabled by
   * default.
   * 
   * @param path External file path.
   * @param streamType The type of the audio stream. Use {@link AudioManager#STREAM_ALARM},
   *            {@link AudioManager#STREAM_DTMF}, {@link AudioManager#STREAM_MUSIC},
   *            {@link AudioManager#STREAM_NOTIFICATION}, {@link AudioManager#STREAM_RING},
   *            {@link AudioManager#STREAM_SYSTEM}, or {@link AudioManager#STREAM_VOICE_CALL}
   */
  public void loadExternalMusic(String path, int streamType) {
    player = new MediaPlayer();
    try {
      player.setDataSource(path);
      player.setAudioStreamType(streamType);
      player.prepare();
      prepared = true;
      player.setLooping(true);
      loaded = true;
      setVolume(1.0f);
    } catch (Exception e) {
      player = null;
      prepared = false;
      throw new RuntimeException(e.getMessage() + "");
    }
  }

  /**
   * Loads music from the specified asset file and prepares the MediaPlayer for playing it. Looping is enabled by
   * default.
   * 
   * @param context Context.
   * @param path File path. Relative to the assets folder.
   */
  public void loadMusicFromAssets(Context context, String path) {
    loadMusicFromAssets(context, path, AudioManager.STREAM_MUSIC);
  }

  /**
   * Loads music from the specified asset file and prepares the MediaPlayer for playing it. Looping is enabled by
   * default.
   * 
   * @param context Context.
   * @param path path File path. Relative to the assets folder.
   * @param streamType The type of the audio stream. Use {@link AudioManager#STREAM_ALARM},
   *            {@link AudioManager#STREAM_DTMF}, {@link AudioManager#STREAM_MUSIC},
   *            {@link AudioManager#STREAM_NOTIFICATION}, {@link AudioManager#STREAM_RING},
   *            {@link AudioManager#STREAM_SYSTEM}, or {@link AudioManager#STREAM_VOICE_CALL}
   */
  public void loadMusicFromAssets(Context context, String path, int streamType) {
    AssetFileDescriptor descriptor = AssetsLoader.getAssetFileDescriptor(context, path);
    player = new MediaPlayer();
    try {
      player.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
      descriptor.close();
      player.setAudioStreamType(streamType);
      player.prepare();
      prepared = true;
      player.setLooping(true);
      loaded = true;
      setVolume(1.0f);
    } catch (Exception e) {
      player = null;
      prepared = false;
      throw new RuntimeException(e.getMessage() + "");
    }
  }

  /**
   * Plays the previously loaded song.<br>
   * If there is not any song loaded, this method does nothing.
   */
  public void play() {
    if (loaded) {
      if (player.isPlaying()) {
        return;
      }
      try {
        synchronized (this) {
          if (!prepared) {
            player.prepare();
          }
          player.start();
        }
      } catch (IllegalStateException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * Pauses the music playback.
   */
  public void pause() {
    if (loaded) {
      if (player.isPlaying()) {
        player.pause();
      }
    }
  }

  /**
   * Stops the music playback.
   */
  public void stop() {
    if (loaded) {
      player.stop();
      synchronized (this) {
        prepared = false;
      }
    }
  }

  /**
   * Returns true if there is a song being played.
   * 
   * @return true if a song is being played, false otherwise
   */
  public boolean isPlaying() {
    return player.isPlaying();
  }

  /**
   * Returns true if the playback is stopped.
   * 
   * @return true if the playback is stopped, false otherwise
   */
  public boolean isStopped() {
    return !prepared;
  }

  /**
   * Releases resources.
   */
  public void release() {
    if (loaded) {
      if (player.isPlaying()) {
        player.stop();
      }
      player.release();
    }
  }

  /**
   * Returns true if looping is enabled.
   * 
   * @return true if looping is enabled, false otherwise
   */
  public boolean isLooping() {
    return player.isLooping();
  }

  /**
   * Enables or disables looping.
   * 
   * @param looping true to enable looping, false to disable it
   */
  public void setLooping(boolean looping) {
    player.setLooping(looping);
  }

  /**
   * Returns the volume of the song being played. If there is no song loaded, this method will return -1.
   * 
   * @return Value between 0.0f and 1.0f. Or -1 if there is no song loaded.
   */
  public float getVolume() {
    if (player != null) {
      return volume;
    }
    return -1;
  }

  /**
   * Sets the volume of the loaded song.
   * 
   * @param volume Volume. Value between 0.0f and 1.0f.
   */
  public void setVolume(float volume) {
    if (player != null) {
      this.volume = volume;
      player.setVolume(volume, volume);
    }
  }

  /**
   * Checks if MusicManager supports playing the specified file.
   * 
   * @param context Context.
   * @param ruta File path.
   * @return true if the file can be played with MusicManager, false otherwise. If the specified path is not a valid
   *         path, this method returns false.
   */
  public static boolean checkFileCompatibility(Context context, String ruta) {
    AssetFileDescriptor descriptor;
    MediaPlayer mp = new MediaPlayer();
    if (ruta.matches("[a-z]+://.+")) {
      try {
        mp.setDataSource(ruta);
        mp.prepare();
      } catch (Exception e) {
        return false;
      }
    } else {
      descriptor = AssetsLoader.getAssetFileDescriptor(context, ruta);
      try {
        mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();
        mp.prepare();
      } catch (Exception e) {
        return false;
      }
    }
    mp.release();
    return true;
  }

}




Java Source Code List

com.miviclin.droidengine2d.AbstractGame.java
com.miviclin.droidengine2d.EngineActivity.java
com.miviclin.droidengine2d.EngineLock.java
com.miviclin.droidengine2d.Engine.java
com.miviclin.droidengine2d.GameThread.java
com.miviclin.droidengine2d.Game.java
com.miviclin.droidengine2d.audio.MusicPlayer.java
com.miviclin.droidengine2d.audio.SoundManager.java
com.miviclin.droidengine2d.gamestate.GameStateAdapter.java
com.miviclin.droidengine2d.gamestate.GameStateManager.java
com.miviclin.droidengine2d.gamestate.GameStateNotRegisteredException.java
com.miviclin.droidengine2d.gamestate.GameState.java
com.miviclin.droidengine2d.gamestate.OnGameStateChangeListener.java
com.miviclin.droidengine2d.graphics.Color.java
com.miviclin.droidengine2d.graphics.DefaultRenderer.java
com.miviclin.droidengine2d.graphics.EngineRenderer.java
com.miviclin.droidengine2d.graphics.GLDebugger.java
com.miviclin.droidengine2d.graphics.GLRenderer.java
com.miviclin.droidengine2d.graphics.GLView.java
com.miviclin.droidengine2d.graphics.Graphics.java
com.miviclin.droidengine2d.graphics.animation.AnimationFrame.java
com.miviclin.droidengine2d.graphics.animation.AnimationStateAdapter.java
com.miviclin.droidengine2d.graphics.animation.AnimationStateListener.java
com.miviclin.droidengine2d.graphics.animation.Animation.java
com.miviclin.droidengine2d.graphics.cameras.Camera.java
com.miviclin.droidengine2d.graphics.cameras.OrthographicCamera.java
com.miviclin.droidengine2d.graphics.material.BlendingOptions.java
com.miviclin.droidengine2d.graphics.material.ColorMaterial.java
com.miviclin.droidengine2d.graphics.material.Material.java
com.miviclin.droidengine2d.graphics.material.TextureColorMaterial.java
com.miviclin.droidengine2d.graphics.material.TextureHsvMaterial.java
com.miviclin.droidengine2d.graphics.material.TextureMaterial.java
com.miviclin.droidengine2d.graphics.material.TransparentTextureMaterial.java
com.miviclin.droidengine2d.graphics.material.UnsupportedMaterialException.java
com.miviclin.droidengine2d.graphics.mesh.ColorMaterialBatchRenderer.java
com.miviclin.droidengine2d.graphics.mesh.Geometry.java
com.miviclin.droidengine2d.graphics.mesh.GraphicsBatchRenderer.java
com.miviclin.droidengine2d.graphics.mesh.RectangleBatchGeometry.java
com.miviclin.droidengine2d.graphics.mesh.RectangleBatchRenderer.java
com.miviclin.droidengine2d.graphics.mesh.TextureColorMaterialBatchRenderer.java
com.miviclin.droidengine2d.graphics.mesh.TextureHsvMaterialBatchRenderer.java
com.miviclin.droidengine2d.graphics.mesh.TextureMaterialBatchRendererBase.java
com.miviclin.droidengine2d.graphics.mesh.TextureMaterialBatchRenderer.java
com.miviclin.droidengine2d.graphics.mesh.TransparentTextureMaterialBatchRenderer.java
com.miviclin.droidengine2d.graphics.shader.ShaderProgramException.java
com.miviclin.droidengine2d.graphics.shader.ShaderProgram.java
com.miviclin.droidengine2d.graphics.shader.ShaderVars.java
com.miviclin.droidengine2d.graphics.text.BitmapFont.java
com.miviclin.droidengine2d.graphics.text.FontChar.java
com.miviclin.droidengine2d.graphics.text.Font.java
com.miviclin.droidengine2d.graphics.text.UndefinedCharacterException.java
com.miviclin.droidengine2d.graphics.texture.TextureAtlas.java
com.miviclin.droidengine2d.graphics.texture.TextureManager.java
com.miviclin.droidengine2d.graphics.texture.TexturePackerAtlas.java
com.miviclin.droidengine2d.graphics.texture.TextureRegion.java
com.miviclin.droidengine2d.graphics.texture.Texture.java
com.miviclin.droidengine2d.input.DefaultKeyEventProcessor.java
com.miviclin.droidengine2d.input.GameInputManager.java
com.miviclin.droidengine2d.input.GameStateInputManager.java
com.miviclin.droidengine2d.input.KeyEventInfo.java
com.miviclin.droidengine2d.input.KeyEventProcessor.java
com.miviclin.droidengine2d.input.KeyProcessor.java
com.miviclin.droidengine2d.input.MotionEventProcessor.java
com.miviclin.droidengine2d.input.TouchProcessor.java
com.miviclin.droidengine2d.input.sensor.AccelerometerValuesListener.java
com.miviclin.droidengine2d.input.sensor.Accelerometer.java
com.miviclin.droidengine2d.input.sensor.SensorUtilities.java
com.miviclin.droidengine2d.resources.AssetsLoader.java
com.miviclin.droidengine2d.util.ActivityUtilities.java
com.miviclin.droidengine2d.util.MutexLock.java
com.miviclin.droidengine2d.util.PrimitiveTypeSize.java
com.miviclin.droidengine2d.util.TransformUtilities.java
com.miviclin.droidengine2d.util.Transform.java
com.miviclin.droidengine2d.util.math.Matrix4.java
com.miviclin.droidengine2d.util.math.MatrixFix.java
com.miviclin.droidengine2d.util.math.Vector2.java
com.miviclin.droidengine2d.util.math.Vector3.java
com.miviclin.droidengine2d.util.time.TimeConstants.java
com.miviclin.droidengine2d.util.time.TimeCounter.java