Example usage for android.media MediaPlayer setAudioStreamType

List of usage examples for android.media MediaPlayer setAudioStreamType

Introduction

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

Prototype

public void setAudioStreamType(int streamtype) 

Source Link

Document

Sets the audio stream type for this MediaPlayer.

Usage

From source file:com.hhunj.hhudata.ForegroundService.java

private MediaPlayer ring() throws Exception, IOException {

    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    MediaPlayer player = new MediaPlayer();

    player.setDataSource(this, alert);

    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {

        player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

        player.setLooping(true);/*from w ww. j  a va  2s  . c om*/

        player.prepare();

        player.start();

    }

    return player;

}

From source file:com.bayapps.android.robophish.playback.LocalPlayback.java

public boolean playNext(QueueItem item) {
    MediaPlayer nextPlayer;
    if (mMediaPlayer == mMediaPlayerA) {
        nextPlayer = mMediaPlayerB;/*from  ww w  .j  av  a2 s. c  o  m*/
    } else
        nextPlayer = mMediaPlayerA;

    String mediaId = item.getDescription().getMediaId();
    boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
    if (mediaHasChanged) {
        mNextMediaId = mediaId;
    }

    MediaMetadataCompat track = mMusicProvider
            .getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));

    //noinspection ResourceType
    String source = track.getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE);

    nextPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
        nextPlayer.setDataSource(source);
    } catch (IOException ex) {
        LogHelper.e(TAG, ex, "Exception playing song");
        if (mCallback != null) {
            mCallback.onError(ex.getMessage());
        }
    }

    // Starts preparing the media player in the background. When
    // it's done, it will call our OnPreparedListener (that is,
    // the onPrepared() method on this class, since we set the
    // listener to 'this'). Until the media player is prepared,
    // we *cannot* call start() on it!
    nextPlayer.prepareAsync();

    mMediaPlayersSwapping = true;
    return true;
}

From source file:com.squalala.talkiewalkie.ui.activities.TalkActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_talk);
    ButterKnife.bind(this);

    connectedUserFragment = new ConnectedUserFragment();
    settingsFragment = new SettingsFragment();

    messageAdapter = new MessageAdapter(messages, new OnClickMessageListener() {
        @Override//from w w w.j  a v  a  2 s.  c  o  m
        public void onClickMessage(Message message) {
            message.setRead(false);
            recyclerView.getAdapter().notifyDataSetChanged();
            mMessages.add(message);
            playAudios();
        }
    });

    linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setStackFromEnd(true);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(messageAdapter);

    progressView.setVisibility(View.VISIBLE);
    btnUserOnline.setVisibility(View.GONE);
    txtWhatHappen.setVisibility(View.GONE);
    //    txtNumberUsers.setVisibility(View.GONE);
    txtWhoSpeak.setVisibility(View.GONE);

    session = ((App) getApplication()).getSession();
    mSocket = ((App) getApplication()).getSocket();
    mSocket.on(Socket.EVENT_CONNECT, onConnect);
    mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    mSocket.on(KEY_NEW_MESSAGE, onNewMessage);
    mSocket.on(KEY_JOIN_ROOM, onJoinRoom);
    mSocket.on(KEY_LEFT_ROOM, onLeftRoom);
    mSocket.on(KEY_NUMBER_USERS, onNumberUsers);
    mSocket.on(KEY_CONNECTED_USERS, onConnectedUsers);

    mSocket.connect();
    /*
            if (session.isBeep())
    iconBeep.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_volume_up_black_48dp));
            else
    iconBeep.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_volume_off_black_48dp));  */

    amanager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

    //   int maxVolume = amanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

    //  System.out.println("Max volume " + maxVolume);
    //  System.out.println("session Max volume " + session.getSoundVolume());
    amanager.setStreamVolume(AudioManager.STREAM_MUSIC, session.getSoundVolume(amanager), 0);

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayerForBeep.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @DebugLog
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            viewAvatar.setVisibility(View.GONE);
            //  pulsator.stop();

            if (session.isAutomaticPlay())
                playAudios();
        }
    });

    mIvVoiceIndicators = new ArrayList<>();
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator1));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator2));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator3));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator4));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator5));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator6));
    mIvVoiceIndicators.add(ButterKnife.<ImageView>findById(this, R.id.mIvVoiceIndicator7));

    mAudioRecorder = AudioRecorder.getInstance();
    mRxAudioPlayer = RxAudioPlayer.getInstance();
    mAudioRecorder.setOnErrorListener(this);

    btnSpeak.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                press2Record();
                break;
            case MotionEvent.ACTION_UP:
                release2Send();
                break;
            case MotionEvent.ACTION_CANCEL:
                release2Send();
                break;
            default:
                break;
            }

            return true;
        }
    });
}

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

private synchronized void doPlay(final DownloadFile downloadFile, int position, boolean start) {
    try {//from   ww w.  jav a  2 s.c  om
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        downloadFile.updateModificationDate();
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(file.getPath());
        setPlayerState(PREPARING);
        mediaPlayer.prepare();
        setPlayerState(PREPARED);

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {

                // Acquire a temporary wakelock, since when we return from
                // this callback the MediaPlayer will release its wakelock
                // and allow the device to go to sleep.
                wakeLock.acquire(60000);

                setPlayerState(COMPLETED);

                // If COMPLETED and not playing partial file, we are *really" finished
                // with the song and can move on to the next.
                if (!file.equals(downloadFile.getPartialFile())) {
                    onSongCompleted();
                    return;
                }

                // If file is not completely downloaded, restart the playback from the current position.
                int pos = mediaPlayer.getCurrentPosition();
                synchronized (DownloadServiceImpl.this) {

                    // Work-around for apparent bug on certain phones: If close (less than ten seconds) to the end
                    // of the song, skip to the next rather than restarting it.
                    Integer duration = downloadFile.getSong().getDuration() == null ? null
                            : downloadFile.getSong().getDuration() * 1000;
                    if (duration != null) {
                        if (Math.abs(duration - pos) < 10000) {
                            LOG.info("Skipping restart from " + pos + " of " + duration);
                            onSongCompleted();
                            return;
                        }
                    }

                    LOG.info("Requesting restart from " + pos + " of " + duration);
                    reset();
                    bufferTask = new BufferTask(downloadFile, pos);
                    bufferTask.start();
                }
            }
        });

        if (position != 0) {
            LOG.info("Restarting player from position " + position);
            mediaPlayer.seekTo(position);
        }

        if (start) {
            mediaPlayer.start();
            setPlayerState(STARTED);
        } else {
            setPlayerState(PAUSED);
        }
        lifecycleSupport.serializeDownloadQueue();

    } catch (Exception x) {
        handleError(x);
    }
}

From source file:com.tsp.clipsy.audio.RingdroidEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename);
    mTitle = metadataReader.mTitle;/*from  www. j a  va  2 s.c o  m*/
    mArtist = metadataReader.mArtist;
    mAlbum = metadataReader.mAlbum;
    mYear = metadataReader.mYear;
    mGenre = metadataReader.mGenre;

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(titleLabel);

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(RingdroidEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));

            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    mProgressDialog.dismiss();
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                mProgressDialog.dismiss();
                e.printStackTrace();
                mInfo.setText(e.toString());

                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mProgressDialog.dismiss();
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                RingdroidEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:com.ringdroid.RingdroidEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename);
    mTitle = metadataReader.mTitle;//from w  w w.  j  av  a2  s  .co  m
    mArtist = metadataReader.mArtist;
    mAlbum = metadataReader.mAlbum;
    mYear = metadataReader.mYear;
    mGenre = metadataReader.mGenre;

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(Utils.convertGBK(titleLabel));

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(RingdroidEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));

            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            mProgressDialog.dismiss();
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                e.printStackTrace();

                Runnable runnable = new Runnable() {
                    public void run() {
                        mProgressDialog.dismiss();
                        mInfo.setText(e.toString());
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    mProgressDialog.dismiss();
                }

            });
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                RingdroidEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:mobi.omegacentauri.ptimer.PTimerEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename);
    mTitle = metadataReader.mTitle;/*from   w ww  .ja  va  2 s.c o m*/
    mArtist = metadataReader.mArtist;
    mAlbum = metadataReader.mAlbum;
    mYear = metadataReader.mYear;
    mGenre = metadataReader.mGenre;

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(titleLabel);

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(PTimerEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));

            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    mProgressDialog.dismiss();
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                mProgressDialog.dismiss();
                e.printStackTrace();
                mInfo.setText(e.toString());

                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mProgressDialog.dismiss();
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                PTimerEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:com.SpeechEd.SpeechEdEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename);
    mTitle = metadataReader.mTitle;/*from w  w w  .  j  av a  2 s  .c  o m*/
    mArtist = metadataReader.mArtist;
    mAlbum = metadataReader.mAlbum;
    mYear = metadataReader.mYear;
    mGenre = metadataReader.mGenre;

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(titleLabel);

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(SpeechEdEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));

            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    mProgressDialog.dismiss();
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                mProgressDialog.dismiss();
                e.printStackTrace();
                mInfo.setText(e.toString());

                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mProgressDialog.dismiss();
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                SpeechEdEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:com.PPRZonDroid.MainActivity.java

/**
 * Play warning sound if airspeed goes below the selected value
 *
 * @param context/*from   ww w  .j  a  v  a  2 s  .c o  m*/
 * @throws IllegalArgumentException
 * @throws SecurityException
 * @throws IllegalStateException
 * @throws IOException
 */
public void play_sound(Context context)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {

    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    MediaPlayer mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setDataSource(context, soundUri);
    final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    //Set volume max!!!
    audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM,
            audioManager.getStreamMaxVolume(audioManager.STREAM_SYSTEM), 0);

    if (audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM) != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    }
}

From source file:com.Beat.RingdroidEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    /* SongMetadataReader metadataReader = new SongMetadataReader(
    this, mFilename);// w  w  w.  j a v a2s  .c o  m
     mTitle = metadataReader.mTitle;
     mArtist = metadataReader.mArtist;
     mAlbum = metadataReader.mAlbum;
     mYear = metadataReader.mYear;
     mGenre = metadataReader.mGenre;*/

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(titleLabel);

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(RingdroidEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));
            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    mProgressDialog.dismiss();
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                mProgressDialog.dismiss();
                e.printStackTrace();
                mInfo.setText(e.toString());

                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mProgressDialog.dismiss();
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                RingdroidEditActivity.this.finish();
            }
        }
    }.start();
}