【已解决】 录音机问题
录音时一共录了12秒多,在录音机播放的页面获取到的log 也是12秒,但是他播放只有4秒,这种问题应该如何去解决。
- player播放.java文件
package com.tblenovo.soundrecorder.filelist.player; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Handler; import android.util.Log; import com.tblenovo.soundrecorder.filelist.listitem.BaseListItem; import com.tblenovo.soundrecorder.filelist.listitem.MediaItem; import com.tblenovo.soundrecorder.notification.NotificationService; import com.tblenovo.soundrecorder.util.NotificationUtils; import java.io.IOException; public class Player implements MediaPlayer.OnCompletionListener,MediaPlayer.OnPreparedListener{ private Context mApplicationContext; // private PlayerPanel mPlayerPanel; // private ImageView mPlayerIcon; // private ProgressBar mPlayerLoading; private MediaItem mMediaItem; private MediaPlayer mPlayer = null; private final static String TAG = "Player"; private static final int UPDATE_FREQ = 1000; private boolean isPrepared = false; private final Handler mHandler = new Handler(); private NotificationUtils mNotificationUtils; private MediaItem.PlayStatus mPlayStatus = MediaItem.PlayStatus.NONE; private Runnable mUpdateProgress = new Runnable() { public void run() { updateUi(); } }; private Runnable mCompletionProgress=new Runnable() { @Override public void run() { if(mNotificationUtils!=null){ mNotificationUtils.cancelNotification(); } destroyPlayer(); } }; private MediaPlayer.OnErrorListener mErrorListener = new MediaPlayer.OnErrorListener() { public boolean onError(MediaPlayer mp, int what, int extra) { mPlayer.reset(); mPlayer.release(); mPlayer =null ; resetUi(); //stopPlayer(); return true; } }; @Override public void onCompletion(MediaPlayer mp) { // stopPlayer(); mHandler.removeCallbacks(mUpdateProgress); mMediaItem.setProgress((int)mMediaItem.getDuration()); Log.d("cfw","(int)mMediaItem.getDuration() ==== " + (int)mMediaItem.getDuration()); // mPlayerPanel.updateProgress(mMediaItem.getDuration(), mMediaItem.getDuration()); mHandler.post(mCompletionProgress); // destroyPlayer(); } public Player(Context context){ mApplicationContext=context.getApplicationContext(); mNotificationUtils=new NotificationUtils(mApplicationContext,this); } /*public void setItemView(View itemView){ if(mPlayerIcon!=null){ mPlayerIcon.setVisibility(View.VISIBLE); } if(mPlayerLoading!=null){ mPlayerLoading.setVisibility(View.INVISIBLE); } mPlayerPanel = (PlayerPanel) itemView.findViewById(R.id.player_panel_layout); mPlayerIcon = (ImageView) itemView.findViewById(R.id.list_icon); mPlayerLoading = (ProgressBar) itemView.findViewById(R.id.list_loading); mPlayerPanel.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(fromUser&&mPlayer!=null){ mPlayer.seekTo((int) (progress*mMediaItem.getDuration()/1000)); mPlayerPanel.updateProgress(mPlayer.getCurrentPosition(), mMediaItem.getDuration()); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }*/ /* * @param item * @return need play item is not changed return false * need play item is changed return true */ public boolean setItem(MediaItem item) { mHandler.removeCallbacks(mCompletionProgress); if(item.equals(mMediaItem)){ return false; } if (mMediaItem != null) { mMediaItem.setPlayStatus(MediaItem.PlayStatus.NONE); } mMediaItem = item; resetUi(); return true; } public MediaItem getMediaItem() { return mMediaItem; } public boolean isItemUsing(BaseListItem item) { if (item instanceof MediaItem) { return item.equals(mMediaItem); } return false; } public void updateUi() { if ( mPlayer != null) { // mPlayerPanel.updateProgress(mPlayer.getCurrentPosition(), mMediaItem.getDuration()); mMediaItem.setProgress(mPlayer.getCurrentPosition()); boolean isPlaying = mPlayer.isPlaying(); if (isPlaying) { mHandler.removeCallbacks(mUpdateProgress); mHandler.postDelayed(mUpdateProgress, UPDATE_FREQ); } mMediaItem.setPlayStatus(mPlayStatus); if(isPrepared){ long cur = Math.round(mPlayer.getCurrentPosition() * 1.0f / 1000); mNotificationUtils.updatePlayerNotification(cur,mMediaItem); } } } private void resetUi() { setPlayStatus(MediaItem.PlayStatus.NONE); mNotificationUtils.cancelNotification(); mMediaItem.setPlayStatus(MediaItem.PlayStatus.NONE); mMediaItem.setProgress(0); // if (mPlayerPanel != null) { // mPlayerPanel.updateProgress(0, mMediaItem.getDuration()); // } } public void startPlayer() { stopPlayer(); Intent service=new Intent(mApplicationContext,NotificationService.class); mApplicationContext.startService(service); mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(mMediaItem.getPath()); Log.d("cfw","mMediaItem.getPath() === " + mMediaItem.getPath()); Log.d("cfw","mPlayer.getCurrentPosition() === " + mMediaItem.getDuration()); mPlayer.setOnCompletionListener(this); mPlayer.setOnErrorListener(mErrorListener); mPlayer.setOnPreparedListener(this); // mPlayerLoading.setVisibility(View.VISIBLE); // mPlayerIcon.setVisibility(View.INVISIBLE); setPlayStatus(MediaItem.PlayStatus.PREPARE); isPrepared = false; mPlayer.prepareAsync(); } catch (IOException e) { mPlayer = null; return; } updateUi(); } public void pausePlayer(boolean isNeedAbandon) { if (mPlayer == null || isPrepared == false) return; if(isNeedAbandon){ abandonAudioFocus(); } mPlayer.pause(); setPlayStatus(MediaItem.PlayStatus.PAUSE); updateUi(); } @Override public void onPrepared(MediaPlayer mp) { if (mPlayer == null) return; //There may be other music stream are playing in background, in order to stop them, //we should get audio focus before start playing int audioFocusResult = requestAudioFocus(); if (AudioManager.AUDIOFOCUS_REQUEST_GRANTED != audioFocusResult) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "requestAudioFocus failed!"); } stopPlayer(); return; } // mPlayerLoading.setVisibility(View.GONE); // mPlayerIcon.setVisibility(View.VISIBLE); setPlayStatus(MediaItem.PlayStatus.PLAYING); isPrepared = true; mPlayer.start(); updateUi(); } public void resumePlayer() { if (mPlayer == null || isPrepared == false) return; requestAudioFocus(); mPlayer.start(); setPlayStatus(MediaItem.PlayStatus.PLAYING); updateUi(); } public void stopPlayer() { abandonAudioFocus(); if (mPlayer == null) return; mPlayer.stop(); mPlayer.release(); mPlayer = null; resetUi(); } public void destroyPlayer() { stopPlayer(); hidePlayer(); } protected void hidePlayer() { if (mMediaItem != null) { mMediaItem.setPlayStatus(MediaItem.PlayStatus.NONE); } } public MediaPlayer getMediaPlayer(){ return mPlayer; } public boolean isPlaying(){ if(mPlayer==null){ return false; } return mPlayer.isPlaying(); } public void onItemDeleted() { stopPlayer(); mMediaItem = null; hidePlayer(); } public void onItemChanged(MediaItem newItem) { mMediaItem = newItem; updateUi(); } private int requestAudioFocus() { AudioManager am = (AudioManager) mApplicationContext.getSystemService(Context.AUDIO_SERVICE); return am.requestAudioFocus(mAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); } private void abandonAudioFocus() { AudioManager am = (AudioManager) mApplicationContext.getSystemService(Context.AUDIO_SERVICE); am.abandonAudioFocus(mAudioFocusChangeListener); } private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { if (AudioManager.AUDIOFOCUS_LOSS == focusChange) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "audio focus loss, stop player"); } stopPlayer(); } if (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT == focusChange) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "audio focus loss transient, pause player"); } pausePlayer(false); } if (AudioManager.AUDIOFOCUS_GAIN == focusChange) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "audio focus gain resume player"); } if(mPlayer!=null&&!mPlayer.isPlaying()){ requestAudioFocus(); resumePlayer(); } } } }; public MediaItem.PlayStatus getPlayStatus() { return mPlayStatus; } public void setPlayStatus(MediaItem.PlayStatus status) { if (mPlayStatus != status) { mPlayStatus = status; } } public void unregisterNotificationReceiver() { if(mNotificationUtils!=null){ mNotificationUtils.unregisterNotificationReceiver(); } } public void seekToFromUser(int progress){ if(mPlayer!=null){ mPlayer.seekTo((int) (progress*mMediaItem.getDuration()/1000)); } } }
2021-03-05 16:31:14.351 14452-14452/com.tblenovo.soundrecorder D/cfw: 进入aac模式 2021-03-05 16:31:14.454 14452-14452/com.tblenovo.soundrecorder D/cfw: mMaxDuration === 0 2021-03-05 16:31:14.454 14452-14452/com.tblenovo.soundrecorder D/cfw: 进入设置编码状态状态 2021-03-05 16:31:14.458 14452-14452/com.tblenovo.soundrecorder D/cfw: 进入prepare状态 2021-03-05 16:31:14.574 14452-14452/com.tblenovo.soundrecorder D/cfw: 进入start状态 2021-03-05 16:31:30.037 14452-14452/com.tblenovo.soundrecorder I/cfw: 此时存储的路径是 ==== /storage/emulated/0/Audio/2021-03-05 04-31-14下午.aac 2021-03-05 16:31:30.038 14452-14452/com.tblenovo.soundrecorder I/cfw: 此时存储的秒数是 ==== 12228 2021-03-05 16:31:30.038 14452-14452/com.tblenovo.soundrecorder I/cfw: 此时存储的mRequestedType是 ==== audio/aac 2021-03-05 16:31:31.633 14452-14452/com.tblenovo.soundrecorder D/cfw: mMediaItem.getPath() === /storage/emulated/0/Audio/2021-03-05 04-31-14下午.aac 2021-03-05 16:31:31.634 14452-14452/com.tblenovo.soundrecorder D/cfw: mPlayer.getCurrentPosition() === 12228 2021-03-05 16:31:36.790 14452-14452/com.tblenovo.soundrecorder D/cfw: (int)mMediaItem.getDuration() ==== 12228 2021-03-05 16:31:39.214 14452-14452/com.tblenovo.soundrecorder D/cfw: mMediaItem.getPath() === /storage/emulated/0/Audio/2021-03-05 04-31-14下午.aac 2021-03-05 16:31:39.215 14452-14452/com.tblenovo.soundrecorder D/cfw: mPlayer.getCurrentPosition() === 12228 2021-03-05 16:31:44.366 14452-14452/com.tblenovo.soundrecorder D/cfw: (int)mMediaItem.getDuration() ==== 12228
Recorder文件 package com.tblenovo.soundrecorder; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.media.AudioManager.OnAudioFocusChangeListener; import android.media.MediaRecorder; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.Log; import com.tblenovo.soundrecorder.scanfile.AudioFileScanUpdater; import com.tblenovo.soundrecorder.util.FileUtils; import com.tblenovo.soundrecorder.util.StorageUtils; import com.tblenovo.soundrecorder.view.VoiceWaveView; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Locale; public class Recorder implements MediaRecorder.OnInfoListener { static final String TAG = "Recorder"; static final String SAMPLE_PREFIX = "recording"; static final String SAMPLE_PATH_KEY = "sample_path"; static final String SAMPLE_LENGTH_KEY = "sample_length"; public static final int IDLE_STATE = 0; public static final int RECORDING_STATE = 1; public static final int PAUSE_STATE = 2; int mState = IDLE_STATE; public static final int NO_ERROR = 0; public static final int SDCARD_ACCESS_ERROR = 1; public static final int INTERNAL_ERROR = 2; public static final int IN_CALL_RECORD_ERROR = 3; public static final int UNSUPPORTED_FORMAT = 4; public static final int RECORD_INTERRUPTED = 5; public static final int RECORD_LOST_FOCUS = 6; public static final int DISK_SPACE_LIMIT = 7; public static final int FILE_SIZE_LIMIT = 8; static final int FOCUSCHANGE = 0; public int mChannels = 0; public int mSamplingRate = 0; private int mBitRate = 0; public String mStoragePath = null; private int mMaxDuration; private int BASE = 1; private float mCurrentDb = 0; private VoiceWaveView mVoiceWaveView; private boolean isPausedByFocusLoss; public interface OnStateChangedListener { public void onStateChanged(int state); public void onError(int error); public void onInfo(int what, int extra); } OnStateChangedListener mOnStateChangedListener = null; MediaRecorder.OnErrorListener mMRErrorListener = new MediaRecorder.OnErrorListener() { public void onError(MediaRecorder mr, int what, int extra) { stop(); setError(RECORD_INTERRUPTED); } }; long mSampleStart = 0; // time at which latest record or play operation started long mSampleLength = 0; // length of current sample File mSampleFile = null; MediaRecorder mRecorder = null; private AudioManager mAudioManager; Context mContext = null; private boolean stopToResume = false; public Recorder(Context context) { if (context.getResources().getBoolean(R.bool.config_storage_path)) { mStoragePath = StorageUtils.applyCustomStoragePath(context); } else { mStoragePath = StorageUtils.getPhoneStoragePath(); } mContext = context; mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE); registerReceiver(); } public void saveState(Bundle recorderState) { recorderState.putString(SAMPLE_PATH_KEY, mSampleFile.getAbsolutePath()); recorderState.putLong(SAMPLE_LENGTH_KEY, mSampleLength); } public int getMaxAmplitude() { if (mState != RECORDING_STATE) return 0; return mRecorder.getMaxAmplitude(); } public void restoreState(Bundle recorderState) { String samplePath = recorderState.getString(SAMPLE_PATH_KEY); if (samplePath == null) return; long sampleLength = recorderState.getLong(SAMPLE_LENGTH_KEY, -1); if (sampleLength == -1) return; File file = new File(samplePath); if (!file.exists()) return; if (mSampleFile != null && mSampleFile.getAbsolutePath().compareTo(file.getAbsolutePath()) == 0) return; delete(); mSampleFile = file; mSampleLength = sampleLength; signalStateChanged(IDLE_STATE); } public void setOnStateChangedListener(OnStateChangedListener listener) { mOnStateChangedListener = listener; } public void setChannels(int nChannelsCount) { mChannels = nChannelsCount; } public void setSamplingRate(int samplingRate) { mSamplingRate = samplingRate; } public void setAudioEncodingBitRate(int bitRate) { mBitRate = bitRate; } public int state() { return mState; } public int progress() { if (mState == RECORDING_STATE) { mSampleLength += (System.currentTimeMillis() - mSampleStart); mSampleStart = System.currentTimeMillis(); return (int) (mSampleLength / 1000); } return 0; } public int sampleLength() { return (int) (mSampleLength / 1000); } public long sampleLengthMillis() { return mSampleLength; } public File sampleFile() { return mSampleFile; } public void renameSampleFile(String newName) { mSampleFile = FileUtils.renameFile(mSampleFile, newName); } /** * Resets the recorder state. If a sample was recorded, the file is deleted. */ public void delete() { stop(); if (mSampleFile != null) mSampleFile.delete(); mSampleFile = null; mSampleLength = 0; signalStateChanged(IDLE_STATE); } /** * Resets the recorder state. If a sample was recorded, the file is left on disk and will * be reused for a new recording. */ public void clear() { stop(); mSampleFile = null; mSampleLength = 0; signalStateChanged(IDLE_STATE); } public void startRecording(int outputfileformat, String extension, Context context, int audiosourcetype, int codectype) { Log.d(TAG, "startRecording: " ); isPausedByFocusLoss = false; stopToResume = false; stop(); if (mSampleFile != null) { mSampleFile.delete(); mSampleFile = null; mSampleLength = 0; } File sampleDir = new File(mStoragePath); if (!sampleDir.exists()) { sampleDir.mkdirs(); } if (!sampleDir.canWrite()) // Workaround for broken sdcard support on the device. sampleDir = new File(StorageUtils.getSdStoragePath(context)); try { /*String prefix = context.getResources().getString(R.string.def_save_name_prefix); if (!"".equals(prefix)) { //long index = FileUtils.getSuitableIndexOfRecording(prefix); //mSampleFile = createTempFile(prefix, Long.toString(index), extension, sampleDir); mSampleFile = createTempFile(context, prefix+"-", extension, sampleDir); } else { prefix = SAMPLE_PREFIX + '-'; mSampleFile = createTempFile(context, prefix, extension, sampleDir); }*/ mSampleFile = createTempFile(context, extension, sampleDir); } catch (IOException e) { setError(SDCARD_ACCESS_ERROR); return; } mRecorder = new MediaRecorder(); mRecorder.setAudioSource(audiosourcetype); //set channel for surround sound recording. if (mChannels > 0) { mRecorder.setAudioChannels(mChannels); } if (mSamplingRate > 0) { mRecorder.setAudioSamplingRate(mSamplingRate); } if (mBitRate > 0) { mRecorder.setAudioEncodingBitRate(mBitRate); } mRecorder.setOutputFormat(outputfileformat); mRecorder.setOnErrorListener(mMRErrorListener); mRecorder.setMaxDuration(mMaxDuration); mRecorder.setOnInfoListener(this); Log.d("cfw", "mMaxDuration === " + mMaxDuration); try { mRecorder.setAudioEncoder(codectype); Log.d("cfw", "进入设置编码状态状态"); } catch(RuntimeException exception) { setError(UNSUPPORTED_FORMAT); mRecorder.reset(); mRecorder.release(); if (mSampleFile != null) mSampleFile.delete(); mSampleFile = null; mSampleLength = 0; mRecorder = null; return; } mRecorder.setOutputFile(mSampleFile.getAbsolutePath()); // Handle IOException try { mRecorder.prepare(); Log.d("cfw", "进入prepare状态"); } catch(IOException exception) { setError(INTERNAL_ERROR); mRecorder.reset(); mRecorder.release(); if (mSampleFile != null) mSampleFile.delete(); mSampleFile = null; mSampleLength = 0; mRecorder = null; return; } // Handle RuntimeException if the recording couldn't start Log.d(TAG,"audiosourcetype " +audiosourcetype); try { mRecorder.start(); updateMicStatus(); Log.d("cfw", "进入start状态"); } catch (RuntimeException exception) { AudioManager audioMngr = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); boolean isInCall = ((audioMngr.getMode() == AudioManager.MODE_IN_CALL) || (audioMngr.getMode() == AudioManager.MODE_IN_COMMUNICATION)); if (isInCall) { Log.d("cfw", "进入catch里面的if判断中"); Log.e(TAG, "startRecording: IN_CALL_RECORD_ERROR"); setError(IN_CALL_RECORD_ERROR); } else { Log.d("cfw", "进入catch里面的else判断中"); setError(INTERNAL_ERROR); } mRecorder.reset(); mRecorder.release(); mRecorder = null; return; } //AQUA-924 fixed by liuxiang8 AudioFileScanUpdater.saveSimpleFilePath(mContext,mSampleFile.getAbsolutePath()); mSampleStart = System.currentTimeMillis(); setState(RECORDING_STATE); stopAudioPlayback(); } public void pauseRecording() { if (mRecorder == null) { return; } try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mRecorder.pause(); } initMicsStatus(); } catch (RuntimeException exception) { setError(INTERNAL_ERROR); Log.e(TAG, "Pause Failed"); } mSampleLength = mSampleLength + (System.currentTimeMillis() - mSampleStart); setState(PAUSE_STATE); } public void resumeRecording() { isPausedByFocusLoss = false; if (mRecorder == null) { return; } stopAudioPlayback(); try { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ mRecorder.resume(); }else{ mRecorder.start(); } updateMicStatus(); } catch (RuntimeException exception) { setError(INTERNAL_ERROR); Log.e(TAG, "Resume Failed"); } mSampleStart = System.currentTimeMillis(); setState(RECORDING_STATE); } public void stopRecording() { if (mRecorder == null) return; try { if ((PAUSE_STATE == mState) && (Build.VERSION.SDK_INT >= 23)){ stopToResume = true; resumeRecording(); setState(RECORDING_STATE); } mRecorder.stop(); initMicsStatus(); }catch (RuntimeException exception){ //setError(INTERNAL_ERROR); stopToResume = false; Log.e(TAG, "Stop Failed"); } mRecorder.reset(); mRecorder.release(); mRecorder = null; mChannels = 0; mSamplingRate = 0; if (mState == RECORDING_STATE) { mSampleLength = mSampleLength + (System.currentTimeMillis() - mSampleStart); } setState(IDLE_STATE); stopToResume = false; } public void stop() { stopRecording(); AudioFileScanUpdater.removeSimpleFilePath(mContext); mAudioManager.abandonAudioFocus(mAudioFocusListener); } private void setState(int state) { if (state == mState) return; mState = state; signalStateChanged(mState); } private void signalStateChanged(int state) { if (mOnStateChangedListener != null) mOnStateChangedListener.onStateChanged(state); } private void setError(int error) { if (mOnStateChangedListener != null) mOnStateChangedListener.onError(error); } public void setStoragePath(String path) { mStoragePath = path; } public File createTempFile(String prefix, String fileName, String suffix, File directory) throws IOException { // Force a prefix null check first if (prefix.length() < 3) { throw new IllegalArgumentException("prefix must be at least 3 characters"); } if (suffix == null) { suffix = ".tmp"; } File tmpDirFile = directory; if (tmpDirFile == null) { String tmpDir = System.getProperty("java.io.tmpdir", "."); tmpDirFile = new File(tmpDir); } File result; do { result = new File(tmpDirFile, prefix + fileName + suffix); } while (!result.createNewFile()); return result; } public File createTempFile(Context context, String prefix, String suffix, File directory) throws IOException { String nameFormat = context.getResources().getString(R.string.def_save_name_format); SimpleDateFormat df = new SimpleDateFormat(nameFormat); String currentTime = df.format(System.currentTimeMillis()); if (!TextUtils.isEmpty(currentTime)) { currentTime = currentTime.replaceAll("[\\\\*|\":<>/?]", "_").replaceAll(" ", "\\\\" + " "); } return createTempFile(prefix, currentTime, suffix, directory); } private File createTempFile(Context context, String suffix, File directory) throws IOException { if (suffix == null) { suffix = ".tmp"; } File tmpDirFile = directory; if (tmpDirFile == null) { String tmpDir = System.getProperty("java.io.tmpdir", "."); tmpDirFile = new File(tmpDir); } String nameFormat = context.getResources().getString(R.string.def_save_name_format); if(!DateFormat.is24HourFormat(mContext)){ nameFormat=context.getResources().getString(R.string.def_save_name_format_12); } SimpleDateFormat df = new SimpleDateFormat(nameFormat, Locale.getDefault()); String currentTime = df.format(System.currentTimeMillis()); if (!TextUtils.isEmpty(currentTime)) { currentTime = currentTime.replaceAll("[\\\\*|\":<>/?]", "_"); } File result; do { result = new File(tmpDirFile, currentTime + suffix); } while (!result.createNewFile()); return result; } public void setMaxDuration(int duration) { mMaxDuration = duration; } @Override public void onInfo(MediaRecorder mr, int what, int extra) { if (mOnStateChangedListener != null) { mOnStateChangedListener.onInfo(what, extra); } } /* * Make sure we're not recording music playing in the background, ask * the MediaPlaybackService to pause playback. */ private void stopAudioPlayback() { AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE); am.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); } private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() { public void onAudioFocusChange(int focusChange) { Log.d(TAG, "audio focus "+focusChange); mRecorderHandler.obtainMessage(FOCUSCHANGE, focusChange, 0) .sendToTarget(); } }; private Handler mRecorderHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case FOCUSCHANGE: switch (msg.arg1) { case AudioManager.AUDIOFOCUS_LOSS: if (state() == Recorder.RECORDING_STATE || state() == Recorder.PAUSE_STATE) { stop(); setError(RECORD_LOST_FOCUS); } break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: if(state() ==Recorder.RECORDING_STATE){ isPausedByFocusLoss = true; pauseRecording(); } break; case AudioManager.AUDIOFOCUS_GAIN: if(state() == Recorder.PAUSE_STATE && isPausedByFocusLoss){ resumeRecording(); } break; default: break; } break; default: break; } } }; /** * update current db value * */ private final Handler mHandler = new Handler(); private Runnable mUpdateMicStatusTimer = new Runnable() { public void run() { updateMicStatus(); } }; private void updateMicStatus() { if (mRecorder != null) { double ratio = (double)mRecorder.getMaxAmplitude() /BASE; mCurrentDb = (float) (20 * Math.log10(ratio)); if (null != mVoiceWaveView) { mVoiceWaveView.setVoiceDb(mCurrentDb); } mHandler.postDelayed(mUpdateMicStatusTimer, VoiceWaveView.ANIMATION_INTERVAL); } } private void initMicsStatus() { mHandler.removeCallbacks(mUpdateMicStatusTimer); if (null != mVoiceWaveView) { mVoiceWaveView.setVoiceDb(0); } } public void setVoiceView(VoiceWaveView voiceWaveView ){ this.mVoiceWaveView=voiceWaveView; } private void registerReceiver(){ IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_TIME_CHANGED); filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); mContext.registerReceiver(mTimeChangedReceiver,filter); } public void unregisterReceiver(){ mContext.unregisterReceiver(mTimeChangedReceiver); } BroadcastReceiver mTimeChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(Intent.ACTION_TIME_CHANGED) || intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)){ if(state()==RECORDING_STATE) { mSampleStart = System.currentTimeMillis() - 1000; } } } }; public boolean isStopToResume(){ return stopToResume; } }
感谢您的回答
您的每一个用心回答,都会让这个世界变得更美好一些!
相关问题
kissmyass ·
Androidstudio
2019-12-18 06:26 847 3
2019-12-21 22:25 821 10
mRecorder.start();这个代码输出一下时间,pause的地方输出一下时间吧。stop也输出一下时间。你这个逻辑我也看不懂[捂脸]各种reset。你可以先把官方的demo跑一下,没问题就移植到自己的代码上即可。
录音时一共录了12秒多
在录音机播放的页面获取到的log 也是12秒
但是他播放只有4秒
把文件拷贝出来,看看文件真正的时长是多少。
另外一个则是操作步骤和log,播放器,录音机,这些都是有状态图的,要处理好状态。
官方demo
https://developer.android.com/guide/topics/media/mediarecorder?hl=zh-cn
以及状态图:
https://developer.android.com/reference/android/media/MediaRecorder