Example usage for android.media MediaPlayer MediaPlayer

List of usage examples for android.media MediaPlayer MediaPlayer

Introduction

In this page you can find the example usage for android.media MediaPlayer MediaPlayer.

Prototype

public MediaPlayer() 

Source Link

Document

Default constructor.

Usage

From source file:com.wsi.audiodemo.ScrollingActivity.java

private void playSound2(String assetName) {
    try {//from   w  w  w. j a  v  a  2 s. co  m
        // Syntax  :  android.resource://[package]/[res type]/[res name]
        // Example : Uri.parse("android.resource://com.my.package/raw/sound1");
        //
        // Syntax  : android.resource://[package]/[resource_id]
        // Example : Uri.parse("android.resource://com.my.package/" + R.raw.sound1);

        String RESOURCE_PATH = ContentResolver.SCHEME_ANDROID_RESOURCE + "://";

        String path;
        if (false) {
            path = RESOURCE_PATH + getPackageName() + "/raw/" + assetName;
        } else {
            int resID = getResources().getIdentifier(assetName, "raw", getPackageName());
            path = RESOURCE_PATH + getPackageName() + File.separator + resID;
        }
        Uri soundUri = Uri.parse(path);
        mSoundName.setText(path);

        mMediaPlayer = new MediaPlayer();
        if (true) {
            mMediaPlayer.setDataSource(getApplicationContext(), soundUri);
            mMediaPlayer.prepare();
        } else if (false) {
            // How to load external audio files.
            // "/sdcard/sample.mp3";
            //  "http://www.bogotobogo.com/Audio/sample.mp3";
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.prepare();
        } else {
            ContentResolver resolver = getContentResolver();
            AssetFileDescriptor afd = resolver.openAssetFileDescriptor(soundUri, "r");
            mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();
        }

        mMediaPlayer.start();
    } catch (Exception ex) {
        Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public void activate(final Context context, final SignedObj obj) {
    Runnable r = new Runnable() {
        @Override/*from ww  w . java  2s  . c om*/
        public void run() {
            byte[] bytes = obj.getRaw();
            if (bytes == null) {
                Pair<JSONObject, byte[]> p = splitRaw(obj.getJson());
                //                content = p.first;
                bytes = p.second;
            }

            /*AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bytes.length, AudioTrack.MODE_STATIC);
            track.write(bytes, 0, bytes.length);
            try { // TODO: hack.
            Thread.sleep(500);
             } catch (InterruptedException e) {
             }
            track.play();
            */
            /****/

            File file = new File(getTempFilename());
            try {
                OutputStream os = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(os);
                bos.write(bytes, 0, bytes.length);
                bos.flush();
                bos.close();

                copyWaveFile(getTempFilename(), getFilename());
                deleteTempFile();

                MediaPlayer mp = new MediaPlayer();

                mp.setDataSource(getFilename());
                mp.prepare();
                mp.start();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    if (context instanceof Activity) {
        ((Activity) context).runOnUiThread(r);
    } else {
        r.run();
    }
}

From source file:com.sourceauditor.sahomemonitor.MainActivity.java

private void playAudio() {
    if (audioPlayer == null) {
        audioPlayer = new MediaPlayer();
        audioPlayer.setOnPreparedListener(this);
        audioPlayer.setOnBufferingUpdateListener(this);
        audioPlayer.setOnErrorListener(this);
    } else {/* w  w w .ja  v a2s.c om*/
        audioPlayer.stop();
        audioPlayer.reset();
    }
    try {
        audioPlayer.setDataSource(this, getAudioUri());
        audioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            logAndDisplayError("Audio in use by another app");
        } else {
            pauseBeforePlaying = false;
            audioPlayer.prepareAsync();
        }
    } catch (IllegalArgumentException e) {
        logAndDisplayError("Illegal argument for audioPlayer");
    } catch (SecurityException e) {
        logAndDisplayError("Security error for audioPlayer");
    } catch (IllegalStateException e) {
        logAndDisplayError("Illegal state exception for audioPlayer");
    } catch (IOException e) {
        logAndDisplayError("IO Error for audio player: " + e.getMessage());
    }
}

From source file:com.phonegap.Capture.java

/**
 * Get the Image specific attributes// w w w.j a v  a 2  s . co m
 * 
 * @param filePath path to the file
 * @param obj represents the Media File Data
 * @param video if true get video attributes as well
 * @return a JSONObject that represents the Media File Data
 * @throws JSONException
 */
private JSONObject getAudioVideoData(String filePath, JSONObject obj, boolean video) throws JSONException {
    MediaPlayer player = new MediaPlayer();
    try {
        player.setDataSource(filePath);
        player.prepare();
        obj.put("duration", player.getDuration());
        if (video) {
            obj.put("height", player.getVideoHeight());
            obj.put("width", player.getVideoWidth());
        }
    } catch (IOException e) {
        Log.d(LOG_TAG, "Error: loading video file");
    }
    return obj;
}

From source file:com.ppdl.microphone.MainActivity.java

public void startPlaying() {
    File file = new File(mMediaFilePath);
    if (file.exists()) {
        Log.i(TAG, "file is: " + file.getAbsolutePath());
        mMediaPlayer = new MediaPlayer();
        try {/*from w  ww  .  ja v  a2 s. c  o  m*/
            mMediaPlayer.setDataSource(mMediaFilePath);
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    Log.i(TAG, "<<<<<<<<<<<< end >>>>>>>>>>>>>>");
                    stopPlaying();
                }
            });
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.schabi.terminightor.NightKillerService.java

private MediaPlayer setupNewMediaPlayer(Alarm alarm) {
    MediaPlayer mediaPlayer = null;//  w  ww.  j  a v  a  2s.  co  m
    try {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(this, Uri.parse(alarm.getAlarmTone()));
        boolean overrideVolume = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean(getString(R.string.overrideAlarmVolume), false);
        if (overrideVolume) {
            mediaPlayer.setVolume(1.0f, 1.0f);
        }
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mediaPlayer.setLooping(true);
        mediaPlayer.prepare();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return mediaPlayer;
}

From source file:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java

@Override
public void onCreate() {
    Util.setUncaughtExceptionHandler(this);
    super.onCreate();

    audioManagerHelper = new AudioManagerHelper(this);
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);

    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override// w w w.j a  v a2s . c o  m
        public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
            handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
            return false;
        }
    });

    if (equalizerAvailable) {
        equalizerController = new EqualizerController(this, mediaPlayer);
        if (!equalizerController.isAvailable()) {
            equalizerController = null;
        } else {
            equalizerController.loadSettings();
        }
    }
    if (visualizerAvailable) {
        visualizerController = new VisualizerController(this, mediaPlayer);
        if (!visualizerController.isAvailable()) {
            visualizerController = null;
        }
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    instance = this;
    lifecycleSupport.onCreate();
}

From source file:com.kasungunathilaka.sarigama.service.PlayerService.java

public void startPlayer(int position) {
    try {//from  ww w. j  a v a2 s  .  c  o  m
        localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_PREPARING));
        slavePlayer = new MediaPlayer();
        slavePlayer.setOnPreparedListener(this);
        slavePlayer.setOnErrorListener(this);
        slavePlayer.setOnCompletionListener(this);
        getSongData(position);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.hansel.myAlert.AlarmFragment.java

private void playSound(Context context, Uri alert) {
    mMediaPlayer = new MediaPlayer();
    try {/*  w ww  .  j  a va  2s .c om*/
        mMediaPlayer.setDataSource(context, alert);
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        }
    } catch (IOException e) {
        System.out.println("Error tocando alarma");
    }
}

From source file:com.lithiumli.fiction.PlaybackService.java

public void play(int index) {
    mQueue.setCurrent(index);//w w  w.j  a  v a2s  . com
    Song song = mQueue.getCurrent();

    Intent intent = new Intent(EVENT_PLAYING);
    intent.putExtra(DATA_SONG, song);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    broadcastPlayState(PlayState.PLAYING);

    Log.d("fiction", "Playing new song");
    try {
        MediaPlayer nextMediaPlayer = new MediaPlayer();
        nextMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        nextMediaPlayer.setDataSource(getApplicationContext(), song.getUri());
        nextMediaPlayer.setOnPreparedListener(this);
        nextMediaPlayer.prepareAsync();
    } catch (IOException e) {
    }
}