Example usage for android.media AudioManager STREAM_MUSIC

List of usage examples for android.media AudioManager STREAM_MUSIC

Introduction

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

Prototype

int STREAM_MUSIC

To view the source code for android.media AudioManager STREAM_MUSIC.

Click Source Link

Document

Used to identify the volume of audio streams for music playback

Usage

From source file:brama.com.hearthum.waveform.WaveformFragment.java

protected void loadFromFile() {
    mFile = new File(mFilename);
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;//w  ww . ja  v  a 2s  .c  o  m
    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener((DialogInterface dialog) -> mLoadingKeepGoing = false);
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = (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
    new Thread() {
        public void run() {
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Log.e(TAG, "Error while creating media player", e);
            }
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);
            } catch (final Exception e) {
                Log.e(TAG, "Error while loading sound file", e);
                mProgressDialog.dismiss();
                mInfo.setText(e.toString());
                return;
            }
            if (mLoadingKeepGoing) {
                mHandler.post(() -> finishOpeningSoundFile());
            }
        }
    }.start();
}

From source file:com.jinfukeji.jinyihuiup.indexBannerClick.ZhiboActivity.java

public void changeAudio(final int i) {
    runOnUiThread(new Runnable() {
        @Override/*from w  w  w.  j av  a 2s  .c o m*/
        public void run() {
            am.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
        }
    });

    //        sp.load(this, seekBar, i);
}

From source file:com.morlunk.mumbleclient.app.PlumbleActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    mSettings = Settings.getInstance(this);
    setTheme(mSettings.getTheme());/*w ww.j a v  a 2  s  . com*/

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setStayAwake(mSettings.shouldStayAwake());

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    preferences.registerOnSharedPreferenceChangeListener(this);

    mDatabase = new PlumbleSQLiteDatabase(this); // TODO add support for cloud storage
    mDatabase.open();

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    mDrawerList.setOnItemClickListener(this);
    mDrawerAdapter = new DrawerAdapter(this, this);
    mDrawerList.setAdapter(mDrawerAdapter);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        @Override
        public void onDrawerClosed(View drawerView) {
            supportInvalidateOptionsMenu();
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            super.onDrawerStateChanged(newState);
            // Prevent push to talk from getting stuck on when the drawer is opened.
            if (getService() != null && getService().isSynchronized() && getService().isTalking()
                    && !mSettings.isPushToTalkToggle()) {
                getService().setTalkingState(false);
            }
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            supportInvalidateOptionsMenu();
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    // Tint logo to theme
    int iconColor = getTheme().obtainStyledAttributes(new int[] { android.R.attr.textColorPrimaryInverse })
            .getColor(0, -1);
    Drawable logo = getResources().getDrawable(R.drawable.ic_home);
    logo.setColorFilter(iconColor, PorterDuff.Mode.MULTIPLY);
    getSupportActionBar().setLogo(logo);

    AlertDialog.Builder dadb = new AlertDialog.Builder(this);
    dadb.setMessage(R.string.disconnectSure);
    dadb.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (mService != null && mService.isConnectionEstablished())
                mService.disconnect();
            loadDrawerFragment(DrawerAdapter.ITEM_FAVOURITES);
        }
    });
    dadb.setNegativeButton(android.R.string.cancel, null);
    mDisconnectPromptBuilder = dadb;

    if (savedInstanceState == null) {
        if (getIntent() != null && getIntent().hasExtra(EXTRA_DRAWER_FRAGMENT)) {
            loadDrawerFragment(getIntent().getIntExtra(EXTRA_DRAWER_FRAGMENT, DrawerAdapter.ITEM_FAVOURITES));
        } else {
            loadDrawerFragment(DrawerAdapter.ITEM_FAVOURITES);
        }
    }

    // If we're given a Mumble URL to show, open up a server edit fragment.
    if (getIntent() != null && Intent.ACTION_VIEW.equals(getIntent().getAction())) {
        String url = getIntent().getDataString();
        try {
            Server server = MumbleURLParser.parseURL(url);

            // Open a dialog prompting the user to connect to the Mumble server.
            DialogFragment fragment = (DialogFragment) ServerEditFragment.createServerEditDialog(
                    PlumbleActivity.this, server, ServerEditFragment.Action.CONNECT_ACTION, true);
            fragment.show(getSupportFragmentManager(), "url_edit");
        } catch (MalformedURLException e) {
            Toast.makeText(this, getString(R.string.mumble_url_parse_failed), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    setVolumeControlStream(
            mSettings.isHandsetMode() ? AudioManager.STREAM_VOICE_CALL : AudioManager.STREAM_MUSIC);

    if (mSettings.isFirstRun())
        showSetupWizard();
}

From source file:nuclei.media.playback.ExoPlayerPlayback.java

/**
 * Try to get the system audio focus./*from   ww w.j a va  2s . c o  m*/
 */
private void tryToGetAudioFocus() {
    LOG.d("tryToGetAudioFocus");
    if (mAudioFocus != AUDIO_FOCUSED) {
        int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            mAudioFocus = AUDIO_FOCUSED;
        }
    }
}

From source file:com.adityarathi.muo.services.AudioPlaybackService.java

/**
 * Initializes the MediaPlayer objects for this service session.
 *//*from  ww  w.  j av  a  2s. c o  m*/
private void initMediaPlayers() {

    /*
     * Release the MediaPlayer objects if they are still valid.
     */
    if (mMediaPlayer != null) {
        mMediaPlayer.release();
        mMediaPlayer = null;
    }

    if (mMediaPlayer2 != null) {
        getMediaPlayer2().release();
        mMediaPlayer2 = null;
    }

    mMediaPlayer = new MediaPlayer();
    mMediaPlayer2 = new MediaPlayer();
    setCurrentMediaPlayer(1);

    getMediaPlayer().reset();
    getMediaPlayer2().reset();

    //Loop the players if the repeat mode is set to repeat the current song.
    if (getRepeatMode() == Common.REPEAT_SONG) {
        getMediaPlayer().setLooping(true);
        getMediaPlayer2().setLooping(true);
    }

    try {
        mMediaPlayer.setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
        getMediaPlayer2().setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
    } catch (Exception e) {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer2 = new MediaPlayer();
        setCurrentMediaPlayer(1);
    }

    //Set the mediaPlayers' stream sources.
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    getMediaPlayer2().setAudioStreamType(AudioManager.STREAM_MUSIC);

}

From source file:com.nbplus.vbroadlauncher.RealtimeBroadcastActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    acquireCpuWakeLock();//w  ww .  ja  va2 s. co m

    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    km.inKeyguardRestrictedInputMode();
    if (km.inKeyguardRestrictedInputMode()) {
        Log.i(TAG, " ??");
        isKeyguardRestrictedInputMode = true;
    } else {
        Log.i(TAG, "   ??");
    }

    mLastNetworkStatus = NetworkUtils.isConnected(this);
    Intent intent = getIntent();
    if (intent == null || !PushConstants.ACTION_PUSH_MESSAGE_RECEIVED.equals(intent.getAction())) {
        Log.d(TAG, "empty or none broadcast intent value ...");
        finishActivity();
        return;
    }

    mBroadcastData = intent.getParcelableExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA);
    if (mBroadcastData == null) {
        Log.d(TAG, ">> payload data is null");
        finishActivity();
        return;
    }

    mBroadcastPayloadIdx = intent.getLongExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, -1);
    Log.d(TAG, ">> onCreate() mBroadcastPayloadIdx= " + mBroadcastPayloadIdx);

    // ? ms  ? ?? ? ?   ?  ????
    // broadcast ? .
    //  ?? ?? ??.
    Intent i = new Intent(this, RealtimeBroadcastActivity.class);
    i.setAction(intent.getAction());
    i.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, mBroadcastData);
    i.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, mBroadcastPayloadIdx);
    LocalBroadcastManager.getInstance(this).sendBroadcast(i);

    IntentFilter filter = new IntentFilter();
    filter.addAction(PushConstants.ACTION_PUSH_MESSAGE_RECEIVED);
    filter.addAction(Constants.ACTION_BROWSER_ACTIVITY_CLOSE);
    LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, filter);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(mBroadcastReceiver, intentFilter);

    hideSystemUI();
    /*
    final Window win = getWindow();
    win.setFlags(
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
            
    win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
    */

    if (Constants.PUSH_PAYLOAD_TYPE_TEXT_BROADCAST.equals(mBroadcastData.getServiceType())) {
        setContentView(R.layout.fragment_text_broadcast);
    } else {
        setContentView(R.layout.fragment_audio_broadcast);
    }
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

    if (Constants.PUSH_PAYLOAD_TYPE_TEXT_BROADCAST.equals(mBroadcastData.getServiceType())) {
        mcheckText2SpeechLister = this;
        // ?
        mTextView = (TextView) findViewById(R.id.broadcast_text);
        mTextView.setText(mBroadcastData.getMessage());
        mTextView.setVerticalScrollBarEnabled(true);
        mTextView.setHorizontalScrollBarEnabled(false);
        mTextView.setMovementMethod(new ScrollingMovementMethod());

        mHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_SETUP_CURRENT_PLAYING, 800);
        Log.d(TAG, "text broadcast = " + mBroadcastData.getMessage());

        mText2SpeechHandler = new TextToSpeechHandler(this, this);
        checkText2SpeechAvailable();
        mIsTTS = true;
    } else {
        // , ??
        mWebView = (WebView) findViewById(R.id.webview);
        mWebViewClient = new RealtimeBroadcastWebViewClient(this, mWebView, this);
        mWebViewClient.setBackgroundTransparent();

        String url = mBroadcastData.getMessage();
        if (url.indexOf("?") > 0) {
            if (!url.contains("UUID=")) {
                url += ("&UUID=" + LauncherSettings.getInstance(this).getDeviceID());
            }
            if (!url.contains("APPID=")) {
                url += ("&APPID=" + getApplicationContext().getPackageName());
            }
        } else {
            if (!url.contains("UUID=")) {
                url += ("?UUID=" + LauncherSettings.getInstance(this).getDeviceID());
            }
            if (!url.contains("APPID=")) {
                if (!url.contains("UUID=")) {
                    url += ("?APPID=" + getApplicationContext().getPackageName());
                } else {
                    url += ("&APPID=" + getApplicationContext().getPackageName());
                }
            }
        }

        mWebViewClient.loadUrl(url);
        mIsTTS = false;
    }
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mStreamMusicVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
    audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
            AudioManager.FLAG_PLAY_SOUND);

    if (Constants.OPEN_BETA_PHONE && LauncherSettings.getInstance(this).isSmartPhone()) {
        StateListener phoneStateListener = new StateListener();
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
}

From source file:net.majorkernelpanic.spydroid.ClientActivity.java

/** Connect to the RTSP server of the remote phone **/
private void connectToServer() {

    // Start video streaming
    if (videoParameters.length() > 0) {
        videoView = new MyVideoView(this);
        videoView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT));
        layoutContainer.addView(videoView);
        videoView.setOnPreparedListener(this);
        videoView.setOnCompletionListener(this);
        videoView.setVideoURI(Uri.parse("rtsp://" + editTextIP.getText().toString() + ":8086/"
                + (videoParameters.length() > 0 ? ("?" + videoParameters) : "")));
        videoView.requestFocus();//from www.  j  av  a2 s.c o  m
    }

    // Start audio streaming
    if (audioParameters.length() > 0) {
        try {
            audioStream.reset();
            audioStream.setDataSource(this, Uri.parse("rtsp://" + editTextIP.getText().toString() + ":8086/"
                    + (audioParameters.length() > 0 ? ("?" + audioParameters) : "")));
            audioStream.setAudioStreamType(AudioManager.STREAM_MUSIC);
            audioStream.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    audioStream.start();
                }
            });
            audioStream.prepareAsync();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            e.printStackTrace();
        }
    }

    Log.e(TAG, "rtsp://" + editTextIP.getText().toString() + ":8086"
            + (videoParameters.length() > 0 ? ("?" + videoParameters) : ""));

}

From source file:com.intel.xdk.player.Player.java

public void unloadAllSounds() {

    Iterator<Entry<String, Integer>> soundPoolNamesAndIdsIter = soundPoolMapName2Id.entrySet().iterator();
    while (soundPoolNamesAndIdsIter.hasNext()) {
        Entry<String, Integer> nameAndId = soundPoolNamesAndIdsIter.next();
        Integer id = nameAndId.getValue();
        String key = nameAndId.getKey();
        soundPoolMapName2Id.remove(key);
        soundPoolMapId2Name.remove(id);
        soundPoolShouldPlay.remove(key);
    }/*from  ww w . j  a va2s. c  om*/
    soundPool.release();
    soundPool = null;
    soundPool = new SoundPool(30, AudioManager.STREAM_MUSIC, 100);

    //      StringBuffer js = new StringBuffer("javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.sound.unload',true,true);ev.name='");
    //      js.append(strRelativeFileURL);
    //      js.append("';e.success=");
    //      js.append(didUnload);
    //      js.append("document.dispatchEvent(ev);");
    //
    //      injectJS(js.toString());
}

From source file:com.grupohqh.carservices.operator.ManipulateCarActivity.java

private void readTag() {
    runOnUiThread(new Runnable() {
        int scantimes = 25;
        String tagId;/*w  w  w. j a  v a 2 s .co m*/
        ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);

        @Override
        public void run() {
            for (int i = 0; i < scantimes; i++) {
                MtiCmd mtiCmd = new CMD_Iso18k6cTagAccess.RFID_18K6CTagInventory(usbCommunication);
                CMD_Iso18k6cTagAccess.RFID_18K6CTagInventory finalCmd = (CMD_Iso18k6cTagAccess.RFID_18K6CTagInventory) mtiCmd;
                if (finalCmd.setCmd(CMD_Iso18k6cTagAccess.Action.StartInventory)) {
                    tagId = finalCmd.getTagId();
                    if (finalCmd.getTagNumber() > 0) {
                        tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                        etEPC.setText(tagId);
                        break;
                    }
                }
            }
            if (etEPC.getText().toString().equals(""))
                etEPC.setHint("No se encontro ningun TAG");
        }
    });
}