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.orange.essentials.otb.ui.OtbTermsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.otb_terms, container, false);
    LinearLayout llayout = (LinearLayout) mView.findViewById(R.id.otb_terms_layout);
    TextView headerTv = (TextView) llayout.findViewById(R.id.otb_header_tv_text);
    headerTv.setText(R.string.otb_home_terms_content);
    List<Term> terms = TrustBadgeManager.INSTANCE.getTerms();

    for (Term term : terms) {
        View layoutToAdd = null;//from w w w.j  a  va 2 s .  co m
        if (term.getTermType() == TermType.VIDEO
                && Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
            layoutToAdd = View.inflate(getActivity(), R.layout.otb_terms_video, null);
            TextView titleTv = (TextView) layoutToAdd.findViewById(R.id.otb_term_video_title);
            final AutoResizingFrameLayout anchorView = (AutoResizingFrameLayout) layoutToAdd
                    .findViewById(R.id.videoSurfaceContainer);
            if (mVideoViews == null) {
                mVideoViews = new ArrayList<>();
            }
            mVideoViews.add(anchorView);
            SurfaceView videoSurface = (SurfaceView) layoutToAdd.findViewById(R.id.videoSurface);

            titleTv.setText(term.getTitleId());

            SurfaceHolder videoHolder = videoSurface.getHolder();
            MediaPlayer player = new MediaPlayer();
            if (mPlayers == null) {
                mPlayers = new ArrayList<>();
            }
            mPlayers.add(player);
            final VideoControllerView controller = new VideoControllerView(getContext());
            VideoCallback videoCallback = new VideoCallback(player, controller, anchorView);
            videoHolder.addCallback(videoCallback);
            anchorView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    controller.show();
                    return false;
                }
            });
            try {
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.setDataSource(getContext(), Uri.parse(getString(term.getContentId())));
                player.setOnPreparedListener(videoCallback);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (term.getTermType() == TermType.TEXT) {//TermType.TEXT
            layoutToAdd = View.inflate(getActivity(), R.layout.otb_terms_text, null);
            TextView titleTv = (TextView) layoutToAdd.findViewById(R.id.otb_term_text_title);
            TextView contentTv = (TextView) layoutToAdd.findViewById(R.id.otb_term_text_content);
            titleTv.setText(term.getTitleId());
            contentTv.setText(Html.fromHtml(getString(term.getContentId())));
            contentTv.setMovementMethod(LinkMovementMethod.getInstance());
            contentTv.setLinkTextColor(getResources().getColor(R.color.colorAccent));
        }
        if (null != layoutToAdd) {
            llayout.addView(layoutToAdd);
        }
        if (terms.indexOf(term) != terms.size() - 1) {
            View.inflate(getActivity(), R.layout.otb_separator, llayout);
        }
    }

    return mView;
}

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

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

    setContentView(R.layout.client);//from  www. ja va 2 s .com

    editTextIP = (EditText) findViewById(R.id.server_ip);
    layoutContainer = (FrameLayout) findViewById(R.id.video_container);
    layoutForm = (RelativeLayout) findViewById(R.id.form);
    layoutControl = (RelativeLayout) findViewById(R.id.control);
    progressBar = (ProgressBar) findViewById(R.id.progress);

    audioStream = new MediaPlayer();

    // Initiate connection with client
    findViewById(R.id.button_connect).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Editor editor = settings.edit();
            editor.putString("last_server_ip", editTextIP.getText().toString());
            editor.commit();
            layoutForm.setVisibility(View.GONE);
            progressBar.setVisibility(View.VISIBLE);
            getCurrentConfiguration();
        }
    });

    // Interrupt connection with the client
    findViewById(R.id.button_stop).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            stopStreaming();
            layoutControl.setVisibility(View.GONE);
            layoutForm.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
        }
    });

    // Show configuration panel
    findViewById(R.id.button_config).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            findViewById(R.id.settings).setVisibility(View.VISIBLE);
        }
    });

    findViewById(R.id.reconnect).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            findViewById(R.id.settings).setVisibility(View.GONE);
            updateSettings();
        }
    });

    // Resolution
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.videoResolutionArray,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    // Framerate
    spinner = (Spinner) findViewById(R.id.spinner2);
    adapter = ArrayAdapter.createFromResource(this, R.array.videoFramerateArray,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    // Bitrate
    spinner = (Spinner) findViewById(R.id.spinner3);
    adapter = ArrayAdapter.createFromResource(this, R.array.videoBitrateArray,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    // Video Encoder
    spinner = (Spinner) findViewById(R.id.spinner4);
    adapter = ArrayAdapter.createFromResource(this, R.array.videoEncoderArray,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    // Audio Encoder
    spinner = (Spinner) findViewById(R.id.spinner5);
    adapter = ArrayAdapter.createFromResource(this, R.array.audioEncoderArray,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    settings = PreferenceManager.getDefaultSharedPreferences(this);
    editTextIP.setText(settings.getString("last_server_ip", "192.168.0.107"));

}

From source file:org.runbuddy.tomahawk.mediaplayers.AndroidMediaPlayer.java

@Override
public void prepare(final Query query, final TomahawkMediaPlayerCallback callback) {
    Log.d(TAG, "prepare() query: " + query);
    mMediaPlayerCallback = callback;//w w w . j ava  2 s  .c o m
    mPreparedQuery = null;
    mPreparingQuery = query;
    if (sMediaPlayer != null) {
        try {
            sMediaPlayer.stop();
        } catch (IllegalStateException e) {
            //ignored
        }
    }
    getStreamUrl(query.getPreferredTrackResult()).done(new DoneCallback<String>() {
        @Override
        public void onDone(String url) {
            Log.d(TAG, "Received stream url: " + url + " for query: " + query);
            if (mPreparingQuery != null && mPreparingQuery == query) {
                Log.d(TAG, "Starting to prepare stream url: " + url + " for query: " + query);
                if (sMediaPlayer != null) {
                    try {
                        sMediaPlayer.stop();
                    } catch (IllegalStateException e) {
                        //ignored
                    }
                    sMediaPlayer.release();
                }
                sMediaPlayer = new MediaPlayer();

                sMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

                try {
                    sMediaPlayer.setDataSource(url);
                    sMediaPlayer.prepare();
                } catch (IOException | IllegalStateException e) {
                    Log.e(TAG, "prepare - ", e);
                    callback.onError(AndroidMediaPlayer.this, "MediaPlayerEncounteredError");
                }

                sMediaPlayer.setOnCompletionListener(new CompletionListener());

                mPreparedQuery = mPreparingQuery;
                mPreparingQuery = null;
                handlePlayState();
                callback.onPrepared(AndroidMediaPlayer.this, mPreparedQuery);
                Log.d(TAG, "onPrepared() url: " + url + " for query: " + query);
            } else {
                Log.d(TAG, "Ignoring stream url: " + url + " for query: " + query
                        + ", because preparing query is: " + mPreparingQuery);
            }
        }
    });
}

From source file:org.amahi.anywhere.service.AudioService.java

private void setUpAudioPlayer() {
    audioPlayer = new MediaPlayer();

    audioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    audioPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);

    audioPlayer.setOnPreparedListener(this);
    audioPlayer.setOnCompletionListener(this);
    audioPlayer.setOnErrorListener(this);
}

From source file:com.orange.ocara.ui.dialog.AudioPlayerDialog.java

void initPlayer() {
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnCompletionListener(this);

    formatBuilder = new StringBuilder();
    formatter = new Formatter(formatBuilder, Locale.getDefault());

    if (progressBar instanceof SeekBar) {
        SeekBar seeker = (SeekBar) progressBar;
        seeker.setOnSeekBarChangeListener(mSeekListener);
    }/*from   w ww.  ja v  a2s. com*/
    progressBar.setMax(1000);

    reset();
}

From source file:com.mylovemhz.simplay.MusicService.java

private void initialize() {
    trackQueue = new ArrayList<>();

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL,
            "music lock");

    ComponentName receiver = new ComponentName(getPackageName(), MediaButtonEventReceiver.class.getName());
    mediaSession = new MediaSessionCompat(this, TAG_MUSIC_SERVICE, receiver, null);
    mediaSession.setFlags(//from  w w  w. j  a  v a 2  s  .c  o  m
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(new SimpleSessionCallback(this));

    currentState = State.IDLE;
    mediaSession.setActive(true);

    isInitialized = true;
    Log.d(TAG_MUSIC_SERVICE, "Initialized...");
}

From source file:com.google.android.gms.samples.vision.face.sleepAlert.DAssistActivity.java

/**
 * Initializes the UI and initiates the creation of a face detector.
 *//*ww  w .ja  v  a 2s  .  co m*/
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
    this.jumbleButton = (Button) findViewById(R.id.Button01);
    this.exitButton = (Button) findViewById(R.id.button);
    this.mp = new MediaPlayer();
    this.tv = (TextView) findViewById(R.id.DisplayMsg);
    this.layout = (RelativeLayout) findViewById(R.id.topLayout);
    this.sc = (CameraSourcePreview) findViewById(R.id.preview);
    this.go = (GraphicOverlay) findViewById(R.id.faceOverlay);
    AssetManager am = getApplicationContext().getAssets();
    AssetFileDescriptor afd = null;
    try {
        afd = am.openFd("Song.mp3");
        this.mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        this.mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource();
    } else {
        requestCameraPermission();
    }
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(final MenuItem menuItem) {
            System.out.println("Srini in onNavigationItemSelected part");
            // Handle navigation view item clicks here.
            int id = menuItem.getItemId();

            if (id == R.id.nav_slideshow) {
                // Handle the camera action
            } else if (id == R.id.nav_manage) {

            } else if (id == R.id.nav_manage_toggle) {

                if (checked == 0) {
                    go.setBackgroundColor(Color.TRANSPARENT);
                    checked = 1;
                } else {
                    go.setBackgroundColor(Color.BLUE);
                    checked = 0;

                }

            }

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }

    });
}

From source file:com.meiste.tempalarm.ui.Alarm.java

@Override
protected void onResume() {
    super.onResume();

    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    // do not play alarms if stream volume is 0 (typically because ringer mode is silent).
    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
        final Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(final MediaPlayer mp, final int what, final int extra) {
                Timber.e("Error occurred while playing audio.");
                mp.stop();//from  w w  w. j  ava2  s  . com
                mp.reset();
                mp.release();
                mMediaPlayer = null;
                return true;
            }
        });
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        try {
            mMediaPlayer.setDataSource(this, alert);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (final IOException e) {
            Timber.e("Failed to play alarm tone: %s", e);
        }
    }

    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(sVibratePattern, 0);

    mPlaying = true;
    mHandler.sendEmptyMessageDelayed(KILLER, ALARM_TIMEOUT);
}

From source file:bupt.tiantian.callrecorder.callrecorder.MainActivity.java

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

    checkPermissions();/*  ww w  .  ja  v a 2  s  .  com*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            //???
            onListFragmentInteraction(new PhoneCallRecord[] {});
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    //set up MediaPlayer
    mediaController = new MediaController(this);
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnCompletionListener(this);

    //        RateMeNowDialog.showRateDialog(this, 10);

}

From source file:org.amahi.anywhere.tv.fragment.TvPlaybackAudioFragment.java

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

    setFadingEnabled(false);// w  ww.  j  a  v  a 2 s  .c o  m

    setBackgroundType(BG_DARK);

    setUpInjections();

    mHandler = new Handler(Looper.getMainLooper());

    setUpRows();

    getAllAudioFiles();

    AudioMetadataRetrievingTask.newInstance(getActivity(), getFileUri(), getAudioFile()).execute();

    mediaPlayer = new MediaPlayer();

    mediaPlayer.setOnCompletionListener(mp -> skipNext());

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    setDataSource();

    prepareAudio();

    mediaPlayer.start();

    setOnItemViewClickedListener((OnItemViewClickedListener) (itemViewHolder, item, rowViewHolder, row) -> {
        if (item instanceof ServerFile) {
            ServerFile serverFile = (ServerFile) item;
            replaceFragment(serverFile);
        }
    });
}