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:ca.uqac.florentinth.speakerauthentication.SettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.activity_settings);

    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    recordingTime = sharedPreferences.getInt("recordingTime", -1);
    chunkLength = sharedPreferences.getInt("chunkLength", -1);
    distanceFromCenter = sharedPreferences.getInt("distanceFromCenter", -1);
    environment = sharedPreferences.getInt("id_environment", -1);

    initGUI();//from ww  w.j a va 2  s  . com
}

From source file:com.dudka.rich.streamingmusicplayer.ServiceMusicPlayer.java

@Override
public int onStartCommand(Intent intent, int flags, int startID) {
    duration = intent.getIntExtra("duration", 0);
    String mediaFile = intent.getStringExtra("media_file");
    try {/*from ww  w.ja  va2 s . co m*/
        player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(mediaFile);
        player.setOnPreparedListener(this);
        player.prepareAsync();
        player.setOnErrorListener(this);
    } catch (Exception e) {
        e.printStackTrace();
        sendLocalBroadcast(MainActivity.PLAYER_ERROR);
    }
    return START_STICKY;
}

From source file:bala.padio.Player.java

private void Play(String url) {
    try {//from  ww w.  j  ava 2  s .  co  m

        if (url == null) {
            Log.e(TAG, "Empty url");
            return;
        }

        // request audio focus
        if (audioManager == null) {
            audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        }
        int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            Log.e(TAG, "Audio focus not granted");
            return;
        }

        // initialize player
        if (mediaPlayer != null) {
            mediaPlayer.reset();
        } else {
            mediaPlayer = new MediaPlayer();
        }

        // set playerUrl source and prepare media player
        this.playerUrl = url;
        Uri streamUrl = Uri.parse(getStreamUrl(url));
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(this, streamUrl);
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.prepareAsync();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.intel.xdk.notification.Notification.java

@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);

    //get convenience reference to activity
    activity = cordova.getActivity();/*from  w  w  w  . java2  s . c om*/

    //init sounds
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);

    //this is needed so that the sound plays the first time
    soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            if (beepCount != -1 && soundPool == Notification.this.soundPool && sampleId == SOUND_BEEP
                    && status == 0) {
                beep(beepCount);
            }
        }
    });

    //SOUND_BEEP = soundPool.load(activity, R.raw.beep, 1);
    SOUND_BEEP = soundPool.load(activity,
            activity.getResources().getIdentifier("xdkbeep", "raw", activity.getPackageName()), 1);
}

From source file:com.mishiranu.dashchan.content.service.AudioPlayerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = new ContextThemeWrapper(this, Preferences.getThemeResource());
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    float density = ResourceUtils.obtainDensity(this);
    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    int padding = getResources().getDimensionPixelSize(R.dimen.dialog_padding_view);
    linearLayout.setPadding(padding, padding, padding, C.API_LOLLIPOP ? (int) (8f * density) : padding);
    textView = new TextView(context, null, android.R.attr.textAppearanceListItem);
    linearLayout.addView(textView, LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    textView.setPadding(0, 0, 0, 0);//w w  w  . java 2  s  . co  m
    textView.setEllipsize(TextUtils.TruncateAt.END);
    textView.setSingleLine(true);
    LinearLayout horizontal = new LinearLayout(context);
    horizontal.setOrientation(LinearLayout.HORIZONTAL);
    horizontal.setGravity(Gravity.CENTER_VERTICAL);
    horizontal.setPadding(0, (int) (16f * density), 0, 0);
    linearLayout.addView(horizontal, LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    seekBar = new SeekBar(context);
    horizontal.addView(seekBar, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
    seekBar.setPadding((int) (8f * density), 0, (int) (16f * density), 0);
    seekBar.setOnSeekBarChangeListener(this);
    button = new ImageButton(context);
    horizontal.addView(button, (int) (48f * density), (int) (48f * density));
    button.setBackgroundResource(
            ResourceUtils.getResourceId(context, android.R.attr.listChoiceBackgroundIndicator, 0));
    setPlayState(false);
    button.setOnClickListener(this);
    alertDialog = new AlertDialog.Builder(context).setView(linearLayout).setOnCancelListener(this)
            .setPositiveButton(R.string.action_stop, this).show();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(AudioPlayerService.ACTION_TOGGLE);
    intentFilter.addAction(AudioPlayerService.ACTION_CANCEL);
    LocalBroadcastManager.getInstance(this).registerReceiver(audioPlayerReceiver, intentFilter);
    bindService(new Intent(this, AudioPlayerService.class), this, 0);
}

From source file:bg.tudle.mtbtimer.ui.MTBMainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    setupActionBar();
}

From source file:com.example.daniel.sounddroid.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //setting up the Mediaplayer
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override/*from   www  .  ja  v a  2 s . com*/
        public void onPrepared(MediaPlayer mp) {
            togglePause();
        }
    });
    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            if ((mSelectedTrackIndex + 1 < mCurrentTracks.size()) && (mSongFromSearch == false)
                    && (mIsInSearch == false)) {
                playTrack(mSelectedTrackIndex + 1, mCurrentTracks);
                Log.d(TAG, "onCompletion: 1");
            } else if ((mSelectedTrackIndex + 1 < mCurrentTracks.size()) && (mSongFromSearch == false)
                    && (mIsInSearch == true)) {
                playTrack(mSelectedTrackIndex + 1, mPreviousTracks);
                Log.d(TAG, "onCompletion: 2");
            } else {
                mPlayerStateButton.setImageResource(R.drawable.ic_play_arrow_white_48px);
                Log.d(TAG, "onCompletion: 3");
            }
        }
    });

    //creating the toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.player_toolbar);
    mSelectedTitle = (TextView) findViewById(R.id.selected_title);
    mSelectedThumbnail = (ImageView) findViewById(R.id.selected_thumbnail);
    mPlayerStateButton = (ImageView) findViewById(R.id.player_state);
    mPlayerStateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            togglePause();
        }
    });

    //setting up the recyclerview and click listener
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.songs_list);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    mCurrentTracks = new ArrayList<Track>();
    mAdapter = new TracksAdapter(this, mCurrentTracks);
    mAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (mSelectedTrack == mCurrentTracks.get(position)) {
                Toast.makeText(MainActivity.this, "This song is already playing", Toast.LENGTH_SHORT).show();
                return;
            }

            mSongFromSearch = mIsInSearch;
            Log.d(TAG, "This song is from search : " + mSongFromSearch + mIsInSearch);
            playTrack(position, mCurrentTracks);
        }
    });

    recyclerView.setAdapter(mAdapter);

    //setting up the soundcloud service and serving default results
    SoundCloudService service = SoundCloud.getService();
    service.searchSongs("like i'm gonna lose you", new Callback<List<Track>>() {
        @Override
        //List<Track> tracks is the result from
        public void success(List<Track> tracks, Response response) {
            updateTracks(tracks);
        }

        @Override
        public void failure(RetrofitError error) {

        }
    });

    //t
    //Using traditional JSONObject and own parsing method
    /*JSONObject jsonObject = null;
    try {
    jsonObject = new JSONObject(trackJSON());
    }catch (JSONException e) {
    }
    Track track = Track.parse(jsonObject);
    Log.d(TAG, track.getmTitle());
    Log.d(TAG, track.getmStreamURL());*/

    //Using Gson library with inbuilt methods
    /*Gson gson = new Gson();
    (Alternate) Track track = gson.fromJson(trackJSON(), Track.class);
    Type type = new TypeToken<List<Track>>(){}.getType();
    List<Track> tracks = gson.fromJson(trackJSON(), type);
    Log.d(TAG, "Track title is " + tracks.get(0).getmTitle());*/
}

From source file:ca.uqac.florentinth.speakerauthentication.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    isUserLogged();/*ww  w  .j ava  2  s .c om*/

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

    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    initGUI();
}

From source file:de.j4velin.headsetturnon.ListeningService.java

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
    if (BuildConfig.DEBUG)
        android.util.Log.d("HeadsetTurnOn", "service start");
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    boolean failed = am.requestAudioFocus(focusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_FAILED;
    am.registerMediaButtonEventReceiver(new ComponentName(ListeningService.this, Receiver.class));

    if (BuildConfig.DEBUG)
        android.util.Log.d("HeadsetTurnOn", "request audiofocus failed? " + failed);

    NotificationCompat.Builder b = new NotificationCompat.Builder(this);
    b.setOngoing(true).setContentText(getString(R.string.notification_text))
            .setContentTitle(getString(R.string.notification_title)).setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(PendingIntent.getActivity(this, 0,
                    new Intent(this, Main.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0));

    startForeground(1, b.build());/*from  ww w . j a v  a  2s  .  com*/

    return START_STICKY;
}

From source file:org.FrancoisDescamps.CatPlayer.MusicService.java

public void playMusic(final String pathToMusic) {
    //register receiver
    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    HeadphonesUnplugReceiver receiver = new HeadphonesUnplugReceiver();
    registerReceiver(receiver, receiverFilter);

    if (mp != null) {
        mp.stop();//w w w.ja  va 2  s.com
        mp = null;
    }

    try {
        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.setDataSource(pathToMusic);
        mp.prepare();
        mp.start();
    } catch (Exception e) {
        /*NOP*/
    }

    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            switch (repeat) {
            case 0: // Lecture en boucle dsactive
                /* NOP */
                break;
            case 1: // Lecture en boucle d'une seule musique
                playMusic(pathToMusic);
                break;
            case 2: // Lecture en boucle de toutes les musiques
                if (positionOfInitialMusic + cpt + 1 == queu.size()) {
                    cpt = 0;
                    positionOfInitialMusic = 0;
                } else {
                    cpt++;
                }
                playMusic(queu.get(positionOfInitialMusic + cpt).getPath());
                break;
            }

            currentTitle = properties[0][positionOfInitialMusic + cpt];
            currentAlbum = properties[1][positionOfInitialMusic + cpt];
            currentArtist = properties[2][positionOfInitialMusic + cpt];
            currentPath = properties[3][positionOfInitialMusic + cpt];

            musicAsChanged = true;
            MainActivity.notifyOtherMusicStarted();
            buildNotification(true);

            //save "cpt"
            editor = preferences.edit();
            editor.putInt("cpt", cpt);

            if (Build.VERSION.SDK_INT < 9) {
                editor.commit();
            } else {
                editor.apply();
            }
        }
    });
}