SoundEffect.java

/*
 * Copyright © 2012 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners.
 * See LICENSE.TXT for license information.
 */
package com.nokia.example.battletank.game.audio;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VolumeControl;

public class SoundEffect {

    private final static String PATH = "/sounds/";
    private final String file;
    private Player player = null;
    private VolumeControl volumeControl;
    public int volume = 0;

    public SoundEffect(String fileName) {
        file = PATH + fileName;
    }

    public void load() {
        if (player != null) {
            return;
        }
        try {
            InputStream is = this.getClass().getResourceAsStream(file);
            player = Manager.createPlayer(is, "audio/mp3");
            player.prefetch();
            volumeControl = (VolumeControl) player.getControl("VolumeControl");
        }
        catch (IOException e) {
        }
        catch (MediaException e) {
        }
    }

    public void close() {
        if (player == null) {
            return;
        }
        player.close();
        player = null;
        volumeControl = null;
    }

    public void play() {
        if (volume > 0) {
            try {
                player.prefetch();
                player.stop();
                player.setMediaTime(0);
                volumeControl.setLevel(volume);
                player.start();
            }
            catch (MediaException ex) {
            }
        }
        volume = 0;
    }

    public void deallocate() {
        player.deallocate();
        volume = 0;
    }
}