Example usage for android.media MediaPlayer create

List of usage examples for android.media MediaPlayer create

Introduction

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

Prototype

public static MediaPlayer create(Context context, int resid) 

Source Link

Document

Convenience method to create a MediaPlayer for a given resource id.

Usage

From source file:org.artoolkit.ar.samples.ARSimple.ARSimple.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*w  w w. j a  va  2s .  c  o m*/
    m0 = MediaPlayer.create(this, R.raw.monson);
    m1 = MediaPlayer.create(this, R.raw.marker1);
    m2 = MediaPlayer.create(this, R.raw.marker2);
    m3 = MediaPlayer.create(this, R.raw.grelot);

    simpleRenderer.bindPlayers(m1, m2);
    mainLayout = (FrameLayout) this.findViewById(R.id.mainLayout);
    seeText = (TextView) this.findViewById(R.id.see);
    searchText = (TextView) this.findViewById(R.id.search);
    playText = (TextView) this.findViewById(R.id.play);

    //searchText.setVisibility(View.GONE);
    seeText.setVisibility(View.GONE);
    playText.setVisibility(View.GONE);

    if (!checkCameraPermission()) {
        //if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { //ASK EVERY TIME - it's essential!
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA },
                MY_PERMISSIONS_REQUEST_CAMERA);
    }

    app = this;

    // When the screen is tapped, inform the renderer and vibrate the phone
    mainLayout.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            searchText.setVisibility(View.GONE);

            simpleRenderer.click(m1);
            Vector<Integer> newSound = DicoSon.getProfile(++profile);
            for (int i = 0; i < newSound.size(); ++i) {

                m0.stop();
                m1.stop();
                m2.stop();
                m3.stop();

                m0.reset();
                m1.reset();
                m2.reset();
                m3.reset();

                m1 = MediaPlayer.create(app, newSound.get(0));
                m2 = MediaPlayer.create(app, newSound.get(1));
                m0 = MediaPlayer.create(app, newSound.get(2));
                m3 = MediaPlayer.create(app, newSound.get(3));
            }

            Toast.makeText(app, "Profil :" + Integer.toString((profile % 4) + 1), Toast.LENGTH_SHORT).show();
            Log.i("Profil :", Integer.toString((profile % 4) + 1));

            /*
                    
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            SoundPool soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
                    
            AssetManager assetManager = getAssets();
                    
            AssetFileDescriptor descriptor=null;
            try {
               descriptor = assetManager.openFd("raw/monson.ogg");
                    
               explosionId = soundPool.load(descriptor, 1);
                    
               soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
                  public void onLoadComplete(SoundPool soundPool, int sampleId,int status) {
             loaded = true;
             soundPool.play(explosionId, 1, 1, 0, 0, 1);
                  }
               });
                    
            } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
            */

            Vibrator vib = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vib.vibrate(40);
        }

    });
}

From source file:me.tipi.kiosk.ui.fragments.OCRFragment.java

@Override
public void onResume() {
    super.onResume();
    // all activity lifecycle events must be passed on to RecognizerView
    if (mRecognizerView != null) {
        mRecognizerView.resume();//w  ww  .  j av a 2 s .  c o  m
    }

    mMediaPlayer = MediaPlayer.create(getActivity(), R.raw.beep);
    mHandler.postDelayed(runnable, ApiConstants.START_OVER_TIME);
}

From source file:edu.cmu.android.restaurant.MapFragment.java

/**
 * //from  w ww  .j  a  v a  2 s.c o  m
 * Shaking: - User shake the mobile to find the coupon of the restaurant in
 * the detail fragment page - After shaking, the mobile vibrates for 500 ms
 * 
 * */
@Override
public void onSensorChanged(SensorEvent event) {

    int sensorType = event.sensor.getType();
    float[] values = event.values;

    if (sensorType == Sensor.TYPE_ACCELEROMETER) {
        if ((Math.abs(values[0]) > 15 || Math.abs(values[1]) > 15 || Math.abs(values[2]) > 15)) {

            Log.d("sensor ", "X- values[0] = " + values[0]);
            Log.d("sensor ", "Y- values[1] = " + values[1]);
            Log.d("sensor ", "Z- values[2] = " + values[2]);

            findDeal();
            dealDisplay();
            /* audio play */
            MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.coupon_audio);
            mp.seekTo(0);
            mp.start();
        }
    }
}

From source file:org.esupportail.nfctagdroid.NfcTacDroidActivity.java

@Override
public void onTagDiscovered(final Tag tag) {
    if (localStorageDBHelper.getValue("readyToScan").equals("ok")) {

        localStorageDBHelper.updateValue("readyToScan", "ko");
        synchronized (tag) {
            String toastText = "";
            int rStatus = R.raw.fail;

            try {
                AuthResultBean authResult = auth(tag);
                toastText = authResult.getMsg();
                if (authResult.isError()) {
                    log.warn(getString(R.string.log_msg_tag_ko));
                    localStorageDBHelper.updateValue("readyToScan", "ok");
                } else {
                    rStatus = R.raw.success;
                    log.info(getString(R.string.log_msg_tag_ok) + " : "
                            + authResult.getMsg().replace("\n", " "));
                }//from  w w w  .  j av  a 2  s . c o  m
            } catch (NfcTagDroidInvalidTagException e) {
                log.info(getString(R.string.log_msg_invalid_auth), e);
                toastText = getString(R.string.msg_tag_ko);
                runOnUiThread(ToastThread.getInstance(getApplicationContext(), rStatus, toastText));

            } catch (NfcTagDroidPleaseRetryTagException e) {
                log.warn(getString(R.string.log_msg_retry_auth), e);
                toastText = getString(R.string.msg_retry);
                runOnUiThread(ToastThread.getInstance(getApplicationContext(), rStatus, toastText));

            } catch (Exception e) {
                log.error(getString(R.string.log_msg_unknow_err), e);
                toastText = getString(R.string.msg_unknow_err);
                runOnUiThread(ToastThread.getInstance(getApplicationContext(), rStatus, toastText));
                localStorageDBHelper.updateValue("readyToScan", "ok");

            }
            MediaPlayer mp = MediaPlayer.create(getApplicationContext(), rStatus);
            mp.start();
        }
    } else {
        log.warn("onTagDiscovered but localStorageDBHelper.getValue(\"readyToScan\") = "
                + localStorageDBHelper.getValue("readyToScan"));
    }

}

From source file:com.markuspage.android.atimetracker.Tasks.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //android.os.Debug.waitForDebugger();
    preferences = getSharedPreferences(TIMETRACKERPREF, MODE_PRIVATE);
    fontSize = preferences.getInt(FONTSIZE, 16);
    concurrency = preferences.getBoolean(CONCURRENT, false);
    if (preferences.getBoolean(MILITARY, true)) {
        TimeRange.FORMAT = new SimpleDateFormat("HH:mm");
    } else {/*from   w w  w. j  av a  2 s.c  o m*/
        TimeRange.FORMAT = new SimpleDateFormat("hh:mm a");
    }

    int which = preferences.getInt(VIEW_MODE, 0);
    if (adapter == null) {
        adapter = new TaskAdapter(this);
        setListAdapter(adapter);
        switchView(which);
    }
    if (timer == null) {
        timer = new Handler();
    }
    if (updater == null) {
        updater = new TimerTask() {
            @Override
            public void run() {
                if (running) {
                    adapter.notifyDataSetChanged();
                    setTitle();
                    Tasks.this.getListView().invalidate();
                }
                timer.postDelayed(this, REFRESH_MS);
            }
        };
    }
    playClick = preferences.getBoolean(SOUND, false);
    if (playClick && clickPlayer == null) {
        clickPlayer = MediaPlayer.create(this, R.raw.click);
        try {
            clickPlayer.prepareAsync();
        } catch (IllegalStateException illegalStateException) {
            // ignore this.  There's nothing the user can do about it.
            Logger.getLogger("TimeTracker").log(Level.SEVERE,
                    "Failed to set up audio player: " + illegalStateException.getMessage());
        }
    }
    decimalFormat = preferences.getBoolean(TIMEDISPLAY, false);
    registerForContextMenu(getListView());
    if (adapter.tasks.isEmpty()) {
        showDialog(HELP);
    }
    vibrateAgent = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    vibrateClick = preferences.getBoolean(VIBRATE, true);

    // Start the notification thread
    this.notificationThread = TaskNotificationThread.getInstance();
    this.notificationThread.init(this, this.adapter);
    this.notificationThread.start();
}

From source file:de.quadrillenschule.azocamsynca.job.JobProcessor.java

public void doTestShots(final TriggerPhotoSerie job) {
    final NikonIR camera = ((AzoTriggerServiceApplication) getActivity().getApplication()).getCamera();
    final JobProcessor jobProcessor = ((AzoTriggerServiceApplication) getActivity().getApplication())
            .getJobProcessor();//from  w w w.ja v a 2  s  .  c o  m

    final AlertDialog.Builder adb = new AlertDialog.Builder(getActivity(), R.style.dialog);
    job.setTriggerStatus(PhotoSerie.TriggerJobStatus.WAITFORUSER);
    adb.setTitle("Test Shots");
    adb.setMessage("This series collects all images during preparation of the project\n" + job.getProject()
            + "\n" + "Camera controls time: " + camera.isExposureSetOnCamera(job.getExposure()));
    if (!job.isToggleIsOpen()) {
        adb.setPositiveButton("Finish", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                job.setTriggerStatus(PhotoSerie.TriggerJobStatus.FINISHED_TRIGGERING);
                jobProcessor.fireJobProgressEvent(job);
                processingLoop();
            }
        });
    }

    adb.setNegativeButton("Trigger", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            camera.trigger();
            if (!camera.isExposureSetOnCamera(job.getExposure())) {
                job.setToggleIsOpen(!job.isToggleIsOpen());

                if (!job.isToggleIsOpen()) {
                    job.setNumber(job.getNumber() + 1);
                    job.setTriggered(job.getTriggered() + 1);

                }

            } else {
                job.setNumber(job.getNumber() + 1);
                job.setTriggered(job.getTriggered() + 1);
            }
            doTestShots(job);
        }
    });
    MediaPlayer mediaPlayer = MediaPlayer.create(activity, R.raw.oida_peda);
    mediaPlayer.start();
    // adb.create().show();
    adb.create();

    alertDialog = adb.show();
}

From source file:com.nfc.gemkey.MainActivity.java

private void playSound(int resId) {
    // Release any resources from previous MediaPlayer
    if (mp != null) {
        mp.release();/* w  w w  . jav  a 2  s.  c  om*/
    }

    // Create a new MediaPlayer to play this sound
    mp = MediaPlayer.create(this, resId);
    mp.setLooping(false);
    mp.start();
}

From source file:dk.bearware.gui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String serverName = getIntent().getStringExtra(ServerEntry.KEY_SERVERNAME);
    if ((serverName != null) && !serverName.isEmpty())
        setTitle(serverName);//  w  w  w  .  ja  v a  2 s  .  c  om
    getActionBar().setDisplayHomeAsUpEnabled(true);

    restarting = (savedInstanceState != null);
    accessibilityAssistant = new AccessibilityAssistant(this);
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mediaButtonEventReceiver = new ComponentName(getPackageName(), MediaButtonEventReceiver.class.getName());
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.setReferenceCounted(false);

    channelsAdapter = new ChannelListAdapter(this.getBaseContext());
    filesAdapter = new FileListAdapter(this, this, accessibilityAssistant);
    textmsgAdapter = new TextMessageAdapter(this.getBaseContext(), accessibilityAssistant);
    mediaAdapter = new MediaAdapter(this.getBaseContext());

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

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(mSectionsPagerAdapter);

    setupButtons();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        final MediaPlayer mMediaPlayer;
        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silence);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mMediaPlayer.release();
            }
        });
        mMediaPlayer.start();
    }
}

From source file:com.fjn.magazinereturncandidate.activities.SdmScannerActivity.java

/**
 * Initialize screen layout//  w  ww  . j av a2s  .co  m
 *
 * @param state {@link Bundle}
 */
@Override
public void onCreate(Bundle state) {

    LogManagerCommon.i(TAG, Message.TAG_SCANNER_ACTIVITY + Message.MESSAGE_ACTIVITY_START);
    super.onCreate(state);

    setContentView(R.layout.activity_sdm_scanner);

    returnMagazineModel = new ReturnMagazineModel();
    csvFileCommon = new CSVFileCommon();
    registerLicenseCommon = new RegisterLicenseCommon();
    maxYearRank = new MaxYearRankEntity();
    checkDataCommon = new CheckDataCommon();
    formatCommon = new FormatCommon();
    strBarcodeOld = "";

    // Load user info
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        //get flag switch OCR
        flagSwitchOCR = bundle.getString(Constants.FLAG_SWITCH_OCR);
        userID = bundle.getString(Constants.COLUMN_USER_ID);
        shopID = bundle.getString(Constants.COLUMN_SHOP_ID);
        serverName = bundle.getString(Constants.COLUMN_SERVER_NAME);
        license = bundle.getString(Constants.COLUMN_LICENSE);
        hashMapArrBook = (HashMap<String, LinkedList<String[]>>) bundle
                .getSerializable(Constants.COLUMN_INFOR_LIST_SCAN);
    }
    // UI init
    UsersEntity user = new UserModel().getUserInfo();
    TextView tvUserName = (TextView) findViewById(R.id.txv_user_name);
    tvUserName.setText(user.getName());

    lvBook = (ListView) findViewById(R.id.list_book);
    arrBookInlist = new LinkedList<>();
    if (hashMapArrBook != null) {
        arrBookInlist = new LinkedList<>(hashMapArrBook.get(Constants.COLUMN_INFOR_LIST_SCAN));
    }

    //Check OCR null
    if (flagSwitchOCR == null) {
        //Flag disable OCR (default)
        flagSwitchOCR = Constants.FLAG_0;
    }
    MaxYearRankModel maxYearRankModel = new MaxYearRankModel();
    DatabaseManagerCommon.initializeInstance(new DatabaseHelper(getApplicationContext()));

    maxYearRank = maxYearRankModel.getMaxYearRank();

    // Init process loading screen
    progress = new ProgressDialog(this);
    progress.setMessage(Message.MESSAGE_UPLOAD_LOG_SCREEN);
    progress.setCancelable(false);

    // Activate HSM license
    ActivationResult activationResult = ActivationManager.activate(this, license);
    Toast.makeText(this, "Activation result: " + activationResult, Toast.LENGTH_LONG).show();

    // HSM init
    hsmDecoder = HSMDecoder.getInstance(this);

    // Declare symbology
    hsmDecoder.enableSymbology(Symbology.EAN13);
    hsmDecoder.enableSymbology(Symbology.EAN13_5CHAR_ADDENDA);
    hsmDecoder.enableSymbology(Symbology.CODE128);
    //hsmDecoder.enableSymbology(Symbology.OCR);
    //hsmDecoder.setOCRActiveTemplate(OCRActiveTemplate.ISBN);

    //create plug-in instance and add a result listener
    customPlugin = new MyCustomPlugin(getApplicationContext(), 100);
    customPlugin.addResultListener(this);
    //register the plug-in with the system
    hsmDecoder.registerPlugin(customPlugin);

    // Declare HSM component UI
    hsmDecoder.enableFlashOnDecode(false);
    hsmDecoder.enableSound(false);
    hsmDecoder.enableAimer(false);
    hsmDecoder.setWindowMode(WindowMode.CENTERING);
    hsmDecoder.setWindow(18, 42, 0, 100);

    // Assign listener
    //hsmDecoder.addResultListener(this);

    // Sound init
    normalSound = MediaPlayer.create(this, R.raw.pingpong_main); // sound is inside res/raw/mysound
    //totalTimeNormalAudio = normalSound.getDuration();

    noReturnSound = MediaPlayer.create(this, R.raw.wrong_main); // sound is inside res/raw/mysound
    //totalTimeNoReturnAudio = noReturnSound.getDuration();

    // Button init
    btnLogout = (Button) findViewById(R.id.btn_logout);
    btnInputJan = (Button) findViewById(R.id.btn_input_jancode);
    btnSend = (Button) findViewById(R.id.btn_send_data);

    aSwitchOCR = (Switch) findViewById(R.id.switch_OCR);
    btnLogout.setOnClickListener(this);
    btnSend.setOnClickListener(this);
    btnInputJan.setOnClickListener(this);
    /*
            aSwitchOCR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (aSwitchOCR.isChecked()) {
            flagSwitchOCR = registerLicenseCommon.EnableOCRDisableJanCode(hsmDecoder);
        } else {
            flagSwitchOCR = registerLicenseCommon.EnableJanCodeDisableOCR(hsmDecoder);
        }
    }
            });*/

    //Check if arr list books not null
    if (arrBookInlist != null) {
        // Set data adapter to list view
        ListViewScanAdapter adapterBook = new ListViewScanAdapter(this, arrBookInlist);
        lvBook.setAdapter(adapterBook);
    }

    //Check network send file and check csvFileCommon.isExistFileCSV()
    if (csvFileCommon.isExistFileCSV() != 0) {
        //Disable scan
        registerLicenseCommon.DisableScan(hsmDecoder);
        //Show dialog choose send data
        showDialogNotifyListCSVWhenLogin();
    }

}

From source file:edu.cmu.android.restaurant.MapFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    /* menu : camera */
    case Menu.FIRST + 1:
        try {//from ww w.j a  va 2 s . c  om
            Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
            startActivityForResult(i, Activity.DEFAULT_KEYS_DIALER);
        } catch (Exception e) {
            Log.d("Detail", "Cemara onClick error.");
        } finally {
            if (getActivity().getResources()
                    .getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT) {
                getActivity().setRequestedOrientation(Configuration.ORIENTATION_PORTRAIT);
            }
        }
        break;

    /* menu : coupon */
    case Menu.FIRST + 2:
        /* display the deal in a dialog */
        findDeal();
        dealDisplay();
        /* audio play */
        MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.coupon_audio);
        mp.seekTo(0);
        mp.start();
        break;

    /* Menu : about */
    case Menu.FIRST + 3:
        Builder builder3 = new AlertDialog.Builder(getActivity());
        builder3.setTitle("About US");
        builder3.setMessage(ABOUT_CONTENT);
        builder3.setPositiveButton("Return", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        }).show();
        break;
    }
    return false;

}