参考:《第一行代码》第8章
########################################################################
在Android中播放音频文件一般都是使用MediaPlayer类来实现,它对多种格式的音频文件提供了非常全面的控制方法,从而使得播放音乐的工作变得非常简单。
常用MediaPlayer类的控制方法:
1.setDataSource():设置要播放的音频文件的位置
2.prepare():在开始播放之前调用这个方法完成准备工作
3.start():开始或继续播放音频
4.pause():暂停播放音频
5.reset():将MediaPlayer对象重置到刚刚创建的状态
6.seekTo():从指定的位置开始播放音频
7.stop():停止播放音频。调用这个方法后的MediaPlayer无法再播放音频
8.release():释放与MediaPlayer对象相关的资源
9.isPlaying():判断当前MediaPlayer是否正在播放音频
10.getDuration():获取载入的音频文件的时长
简单的工作流程:首先需要创建出一个MediaPlayer对象,然后调用setDataSource()方法来设置音频文件的路径,再调用prepare()方法使MediaPlayer进入到准备状态,接下来调用start()方法就可以开始播放音频,调用pause()方法就会暂停播放,调用reset()方法就会停止播放。
新建项目AudioTest
MainActivity.java:
package com.zj.audiotest; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import java.io.File; public class MainActivity extends Activity implements View.OnClickListener { private Button play; private Button pause; private Button stop; private MediaPlayer mediaPlayer = new MediaPlayer(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); play = (Button)findViewById(R.id.play); pause = (Button)findViewById(R.id.pause); stop = (Button)findViewById(R.id.stop); play.setOnClickListener(this); pause.setOnClickListener(this); stop.setOnClickListener(this); initMediaPlayer(); //initialize } private void initMediaPlayer() { try { File file = new File(Environment.getExternalStorageDirectory(), "music.mp3"); mediaPlayer.setDataSource(file.getPath()); //Specify the path for the audio file mediaPlayer.prepare(); //Let MediaPlayer enter the ready state } catch (Exception e) { e.printStackTrace(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.play: if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); //start playing } break; case R.id.pause: if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); //pause playback } break; case R.id.stop: if (mediaPlayer.isPlaying()) { mediaPlayer.reset(); //stop playing and return to the state of the uninialization initMediaPlayer(); //initialize } break; default: break; } } @Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } } }
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/play" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Play" /> <Button android:id="@+id/pause" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Pause" /> <Button android:id="@+id/stop" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Stop" /> </LinearLayout>
在AndroidManifest.xml上加入:
<!-- 访问外部存储的权限 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
震动VIBRATE:
long VIBRATE_DURATIN = 200L; Vibrator vibrate = (Vibrator)getSystemService(VIBRATOR_SERVICE); vibrate.vibrate(VIBRATE_DURATIN);
<!-- permission to vibrate --> <uses-permission android:name="android.permission.VIBRATE" />
函数解析:
/** * Use with {@link #getSystemService} to retrieve a {@link * android.os.Vibrator} for interacting with the vibration hardware. * * @see #getSystemService * @see android.os.Vibrator */ public static final String VIBRATOR_SERVICE = "vibrator";
/** * Vibrate constantly for the specified period of time. * <p>This method requires the caller to hold the permission * {@link android.Manifest.permission#VIBRATE}. * * @param milliseconds The number of milliseconds to vibrate. */ public void vibrate(long milliseconds) { vibrate(milliseconds, null); }
android.permission.VIBRATE参数milliseconds表示振动的毫秒数
##################################################################################
二维码模块的音频播放和震动:
修改上面AudioTest项目:
MainActivity.java如下:
package com.zj.audiotest; import android.app.Activity; import android.content.res.AssetFileDescriptor; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Vibrator; import android.view.View; import android.widget.Button; import java.io.IOException; public class MainActivity extends Activity implements View.OnClickListener { private MediaPlayer mediaPlayer; private boolean playBeep; private static final float BEEP_VOLUME = 0.10f; private boolean vibrate; private Button btnVibrate; private static final long VIBRATE_DURATION = 200L; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnVibrate = (Button)findViewById(R.id.vibrate); btnVibrate.setOnClickListener(this); playBeep = true; AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE); if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) { playBeep = false; } initBeepSound(); vibrate = true; } private void initBeepSound() { if (playBeep && mediaPlayer == null) { // The volume on STREAM_SYSTEM is not adjustable, and users found it // too loud, // so we now play on the music stream. setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mediaPlayer.setOnCompletionListener(beepListener); AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); file.close(); mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); } catch (IOException e) { mediaPlayer = null; } } } /** * When the beep has finished playing, rewind to queue up another one. */ private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.seekTo(0); } }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.vibrate: playBeepSoundAndVibrate(); break; default: break; } } public void playBeepSoundAndVibrate() { if (playBeep && mediaPlayer != null) { mediaPlayer.start(); } if (vibrate) { Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(VIBRATE_DURATION); } } @Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/vibrate" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Vib" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.zj.audiotest" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <!-- 访问外部存储的权限 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- permission to vibrate --> <uses-permission android:name="android.permission.VIBRATE" /> </manifest>