List of usage examples for android.media MediaPlayer MediaPlayer
public MediaPlayer()
From source file:com.metinkale.prayerapp.vakit.AlarmReceiver.java
public static MediaPlayer play(Context c, String sound) throws IOException { Uri uri = Uri.parse(sound);// www. j a v a2 s .co m MediaPlayer mp = new MediaPlayer(); mp.setLooping(false); mp.setDataSource(c, uri); mp.setAudioStreamType(getStreamType(c)); mp.prepare(); mp.start(); return mp; }
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 w w w .j a va 2 s . c om 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:com.zetterstrom.android.soundboarder.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setTitle("Ultimate Soundboard"); mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawer_layout); mMediaPlayer = new MediaPlayer(); mTitle = getTitle();//ww w .ja va 2s. co m mBoardsTitles = getResources().getStringArray(R.array.boards_array); mDrawerList = (ListView) findViewById(R.id.main_left_drawer); // set a custom shadow that overlays the main content when the drawer // opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mBoardsTitles)); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { ActivityCompat.invalidateOptionsMenu(MainActivity.this); // creates // call // to // onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { ActivityCompat.invalidateOptionsMenu(MainActivity.this); // creates // call // to // onPrepareOptionsMenu() } }; // Set the drawer toggle as the DrawerListener mDrawerLayout.setDrawerListener(mDrawerToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); if (savedInstanceState != null) { mPosition = savedInstanceState.getInt("soundBoardPosition"); } else { SharedPreferences settings = getSharedPreferences(PREFS_FILE, MODE_PRIVATE); mPosition = settings.getInt("soundBoardPosition", 0); } selectItem(mPosition); }
From source file:edu.chl.dat255.sofiase.readyforapet.viewcontroller.CreatePetActivity.java
/** * When pressing the button create it checks whether the user has typed a name, and then creates an instance of the Pet class. * /*from w w w . j av a2s . c o m*/ */ public void onClick(View v) { EditText setName = (EditText) findViewById(R.id.edit_pet_name); petName = setName.getText().toString(); //Starts a dog barking sound when a new pet is created try { afd = getAssets().openFd("dogbarks.wav"); player = new MediaPlayer(); player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); player.prepare(); player.start(); } catch (IOException e) { e.printStackTrace(); } //Makes sure the user has typed in a name if (petName.equals("")) { Toast.makeText(this, "Give your pet a name!", Toast.LENGTH_SHORT).show(); } else { //Creating a new dog with total initial startmood 8 dog = new Dog(petName, 2, 2, 2, 2); startActivity(new Intent(CreatePetActivity.this, PetActivity.class)); } }
From source file:edu.chl.dat255.sofiase.readyforapet.viewcontroller.SleepActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sleep); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Show the Up button in the action bar. setupActionBar();//from w w w .j a v a 2s. c o m startSleeping = (Button) findViewById(R.id.startsleeping); stopSleeping = (Button) findViewById(R.id.stopsleeping); sleepingDog = (ImageView) findViewById(R.id.sleepingdog); stopSleeping.setEnabled(false); startSleeping.setOnClickListener(new OnClickListener() { /** * Method onClick for the start sleeping button * * @param v - View */ public void onClick(View v) { //Snooring starts when clicking on fall asleep try { afd = getAssets().openFd("snoresoundsdog.wav"); player = new MediaPlayer(); player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); player.prepare(); player.start(); } catch (IOException e) { e.printStackTrace(); } stopSleeping.setEnabled(true); startSleeping.setEnabled(false); //Getting the time the pet starts to sleep startHour = CreatePetActivity.getPet().getPetMood().getCurrentHour(); sleepingDog.setVisibility(View.VISIBLE); sleepingDog.setBackgroundResource(R.anim.animation5); anim = (AnimationDrawable) sleepingDog.getBackground(); anim.start(); uiHandler.postDelayed(makeViewStop, 12000); } }); stopSleeping.setOnClickListener(new OnClickListener() { /** * Method onClick for the stop sleeping * * @param v - View */ public void onClick(View v) { //Calculating for how long the dog has slept if (startHour != 0) { sleepHours = (int) ((CreatePetActivity.getPet().getPetMood().getCurrentHour()) - startHour); } //Setting a resultCode with the distance walked that is sent to PetActivity SleepActivity.this.setResult(sleepHours); SleepActivity.this.finish(); } }); }
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();/*from w w w. j a v a2s . c om*/ 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(); } } }); }
From source file:com.reallynourl.nourl.fmpfoldermusicplayer.backend.MediaService.java
private void setupMediaPlayer(ExtendedFile file) { mIsPreparedToPlay = false;/* ww w . jav a2 s. c o m*/ mCurrentFile = file; if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnErrorListener(this); mMediaPlayer.setOnInfoListener(this); } else { if (mMediaPlayer.isPlaying()) mMediaPlayer.stop(); mMediaPlayer.reset(); } try { mMediaPlayer.setDataSource(getApplicationContext(), Uri.fromFile(file)); } catch (IOException e) { Toast.makeText(getApplicationContext(), "Failed to load the file.", Toast.LENGTH_LONG).show(); return; } mMediaPlayer.prepareAsync(); }
From source file:bala.padio.Player.java
private void Play(String url) { try {/*from ww w . j a va2s. c o 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.melonbear.ampup.MediaSectionFragment.java
private void startPlaying() { mPlayer = new MediaPlayer(); OnCompletionListener completionListener = new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { mPlayButton.setText("Start Playing"); mPlayButton.mStartPlaying = !mPlayButton.mStartPlaying; Log.i(LOG_TAG, "Finished Playing"); }/*from w w w .j av a 2 s . c o m*/ }; mPlayer.setOnCompletionListener(completionListener); try { mPlayer.setDataSource(mFileName); mPlayer.prepare(); mPlayer.start(); } catch (IOException e) { Log.e(LOG_TAG, "prepare() failed"); } }
From source file:com.racoon.ampdroid.Mp3PlayerService.java
@Override public void onCreate() { mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(new SongComplitionListener()); pause = false;// w w w . ja v a2 s. c o m session = ""; }