Android 音视频录制

Android音频,视频录制,涉及到AudioRecorder,MediaRecorder,其中,AudioRecorder只能录制声音,MediaRecorder可以录制声音和视频。还有许多音视频编码格式,文件格式等,详见https://developer.android.com/guide/topics/media/media-formats.html。整理的音视频录制,及播放,Android 7.0 亲测代码,可运行(其中SurfaceView需要具体指定)。转载请载明出处,https://blog.csdn.net/sdbzmyh0/article/details/79947850

邮箱:sdbzmyh@163.com,qq:279931514,微信:sdbzmyh

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2018-04-11.
 */
public class MediaUtil{
    MediaRecorder mediarecorder;
    SurfaceView surfaceView=null;//需要在Activity中指定
    SurfaceHolder surfaceHolder=null;
    MediaPlayer mediaPlayer;
    File mAudioFile;
    String mFilePath;
    long startTime;
    private void recordAudioAAC() {
        //创建MediaRecorder对象
        mediarecorder = new MediaRecorder();
        //创建录音文件,.m4a为MPEG-4音频标准的文件的扩展名
        mAudioFile = new File(mFilePath + System.currentTimeMillis() + ".m4a");
        //创建父文件夹
        mAudioFile.getParentFile().mkdirs();
        try {
            //创建文件
            mAudioFile.createNewFile();
            //配置mMediaRecorder相应参数
            //从麦克风采集声音数据
            mediarecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            //设置保存文件格式为MP4
            mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            //设置采样频率,44100是所有安卓设备都支持的频率,频率越高,音质越好,当然文件越大
            mediarecorder.setAudioSamplingRate(44100);
            //设置声音数据编码格式,音频通用格式是AAC
            mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            //设置编码频率
            mediarecorder.setAudioEncodingBitRate(96000);
            //设置录音保存的文件
            mediarecorder.setOutputFile(mAudioFile.getAbsolutePath());
            //开始录音
            mediarecorder.prepare();
            mediarecorder.start();
            //记录开始录音时间
            startTime = System.currentTimeMillis();
        } catch (Exception e) {
            e.printStackTrace();
            mediarecorder.stop();
            if (null != mediarecorder) {
                mediarecorder.release();
                mediarecorder = null;
            }
        }
    }
    private void Media3gp(){
        mediarecorder = new MediaRecorder();

                /*Camera camera = Camera.open();
                Camera.Parameters parameters = camera.getParameters();
//              parameters.setRotation(90);
                parameters.setPreviewSize(640, 480);
                parameters.setPictureSize(640, 480);
                camera.setParameters(parameters);
                camera.setDisplayOrientation(90);
                camera.unlock();
                mediarecorder.setCamera(camera);
                mediarecorder.reset();*/

        /*mediarecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
            @Override
            public void onInfo(MediaRecorder mr, int what, int extra) {

            }
        });
        mediarecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
            @Override
            public void onError(MediaRecorder mr, int what, int extra) {

            }
        });*/
        /*mediarecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);*/

        mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        //mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        mediarecorder.setVideoSize(640,480);
        //mediarecorder.setVideoFrameRate(20);
                /*CamcorderProfile cProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
                mediarecorder.setProfile(cProfile);*/
        //mediarecorder.setVideoEncodingBitRate(9995*1024*1024);// 设置帧频率,然后就清晰了
        mediarecorder.setVideoEncodingBitRate(5*1920*1080);// 设置帧频率,然后就清晰了
        //mediarecorder.setOrientationHint(90);// 输出旋转90度,保持竖屏录制

        mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());
        mediarecorder.setOutputFile("/sdcard/text.3gp");
        //mediarecorder.setOutputFile("/sdcard/love.mp4");
        try {
            mediarecorder.prepare();
            mediarecorder.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void MediaMp4(){
        if(mediarecorder==null){
            mediarecorder = new MediaRecorder();
        }

        /*camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        if (camera != null) {
            camera.setDisplayOrientation(90);
            camera.unlock();
            mediarecorder.setCamera(camera);
        }*/

        try {
            // 这两项需要放在setOutputFormat之前
            //mediarecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mediarecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

            // Set output file format
            mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

            // 这两项需要放在setOutputFormat之后
            mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

            //CamcorderProfile cProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            /*CamcorderProfile cProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_2160P);
            mediarecorder.setProfile(cProfile);*/
            mediarecorder.setVideoSize(640, 480);
            //mediarecorder.setVideoFrameRate(30);
            mediarecorder.setVideoEncodingBitRate(5000 * 1024 * 1024);
            //mediarecorder.setOrientationHint(90);
            //设置记录会话的最大持续时间(毫秒)
            //mediarecorder.setMaxDuration(30 * 1000);
            mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());

            mediarecorder.setOutputFile("/sdcard/text.mp4");
            mediarecorder.prepare();
            mediarecorder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void startPlay(File mFile) {
        try {
            //初始化播放器
            mediaPlayer = new MediaPlayer();
            //设置播放音频数据文件
            mediaPlayer.setDataSource(mFile.getAbsolutePath());
            //设置播放监听事件
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    //播放完成
                    playEndOrFail(true);
                }
            });
            //播放发生错误监听事件
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    playEndOrFail(false);
                    return true;
                }
            });
            //播放器音量配置
            mediaPlayer.setVolume(1, 1);
            //是否循环播放
            mediaPlayer.setLooping(false);
            //准备及播放
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
            //播放失败正理
            playEndOrFail(false);
        }

    }
    private static final int RECORD_SUCCESS=0,RECORD_FAIL=1,RECORD_TOO_SHORT=3,PLAY_COMPLETION=4,PLAY_ERROR=5;
    private void playEndOrFail(boolean isEnd) {
        if (isEnd) {
            mHandler.sendEmptyMessage(PLAY_COMPLETION);
        } else {
            mHandler.sendEmptyMessage(PLAY_ERROR);
        }
        if (null != mediaPlayer) {
            mediaPlayer.setOnCompletionListener(null);
            mediaPlayer.setOnErrorListener(null);
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case RECORD_SUCCESS:
                    break;
                case RECORD_FAIL:
                    break;
                case RECORD_TOO_SHORT:
                    break;
                case PLAY_COMPLETION:
                    break;
                case PLAY_ERROR:
                    break;

            }
        }
    };
}

Android 官方音视频对应格式

https://developer.android.com/guide/topics/media/media-formats.html

Supported Media Formats

This document describes the media codec, container, and network protocol support provided by the Android platform.

As an application developer, you can use any media codec that is available on any Android-powered device, including those provided by the Android platform and those that are device-specific. However, it is a best practice to use media encoding profiles that are device- agnostic.

The tables below describe the media format support built into the Android platform. Codecs that are not guaranteed to be available on all Android platform versions are noted in parentheses, for example: (Android 3.0+). Note that any given mobile device might support other formats or file types that are not listed in the table.

Section 5 of the Android Compatibility Definition specifies the media formats a device must support to be compatible with Android 8.1.

Audio support


Audio formats and codecs

Format / CodecEncoderDecoderDetailsSupported File Type(s) / Container Formats
AAC LCSupport for mono/stereo/5.0/5.1 content with standard sampling rates from 8 to 48 kHz.• 3GPP (.3gp)
• MPEG-4 (.mp4, .m4a)
• ADTS raw AAC (.aac, decode in Android 3.1+, encode in Android 4.0+, ADIF not supported)
• MPEG-TS (.ts, not seekable, Android 3.0+)
HE-AACv1 (AAC+)
(Android 4.1+)
HE-AACv2 (enhanced AAC+) Support for stereo/5.0/5.1 content with standard sampling rates from 8 to 48 kHz.
AAC ELD (enhanced low delay AAC)
(Android 4.1+)

(Android 4.1+)
Support for mono/stereo content with standard sampling rates from 16 to 48 kHz
AMR-NB4.75 to 12.2 kbps sampled @ 8kHz3GPP (.3gp)
AMR-WB9 rates from 6.60 kbit/s to 23.85 kbit/s sampled @ 16kHz3GPP (.3gp)
FLAC
(Android 4.1+)

(Android 3.1+)
Mono/Stereo (no multichannel). Sample rates up to 48 kHz (but up to 44.1 kHz is recommended on devices with 44.1 kHz output, as the 48 to 44.1 kHz downsampler does not include a low-pass filter). 16-bit recommended; no dither applied for 24-bit.FLAC (.flac) only
MIDI MIDI Type 0 and 1. DLS Version 1 and 2. XMF and Mobile XMF. Support for ringtone formats RTTTL/RTX, OTA, and iMelody• Type 0 and 1 (.mid, .xmf, .mxmf)
• RTTTL/RTX (.rtttl, .rtx)
• OTA (.ota)
• iMelody (.imy)
MP3 Mono/Stereo 8-320Kbps constant (CBR) or variable bit-rate (VBR)MP3 (.mp3)
Opus 
(Android 5.0+)
 Matroska (.mkv)
PCM/WAVE
(Android 4.1+)
8- and 16-bit linear PCM (rates up to limit of hardware). Sampling rates for raw PCM recordings at 8000, 16000 and 44100 Hz.WAVE (.wav)
Vorbis  • Ogg (.ogg)
• Matroska (.mkv, Android 4.0+)

Video support


Video formats and codecs

Format / CodecEncoderDecoderDetailsSupported File Type(s) / Container Formats
H.263Support for H.263 is optional in Android 7.0+• 3GPP (.3gp)
• MPEG-4 (.mp4)
H.264 AVC
Baseline Profile (BP)

(Android 3.0+)
 • 3GPP (.3gp)
• MPEG-4 (.mp4)
• MPEG-TS (.ts, AAC audio only, not seekable, Android 3.0+)
H.264 AVC
Main Profile (MP)

(Android 6.0+)
The decoder is required, the encoder is recommended. 
H.265 HEVC 
(Android 5.0+)
Main Profile Level 3 for mobile devices and Main Profile Level 4.1 for Android TV• MPEG-4 (.mp4)
MPEG-4 SP  3GPP (.3gp)
VP8
(Android 4.3+)

(Android 2.3.3+)
Streamable only in Android 4.0 and above• WebM (.webm)
• Matroska (.mkv, Android 4.0+)
VP9 
(Android 4.4+)
 • WebM (.webm)
• Matroska (.mkv, Android 4.0+)

Video encoding recommendations

The table below lists the Android media framework video encoding profiles and parameters recommended for playback using the H.264 Baseline Profile codec. The same recommendations apply to the Main Profile codec, which is only available in Android 6.0 and later.

 SD (Low quality)SD (High quality)HD 720p (N/A on all devices)
Video resolution176 x 144 px480 x 360 px1280 x 720 px
Video frame rate12 fps30 fps30 fps
Video bitrate56 Kbps500 Kbps2 Mbps
Audio codecAAC-LCAAC-LCAAC-LC
Audio channels1 (mono)2 (stereo)2 (stereo)
Audio bitrate24 Kbps128 Kbps192 Kbps

The table below lists the Android media framework video encoding profiles and parameters recommended for playback using the VP8 media codec.

 SD (Low quality)SD (High quality)HD 720p (N/A on all devices)HD 1080p (N/A on all devices)
Video resolution320 x 180 px640 x 360 px1280 x 720 px1920 x 1080 px
Video frame rate30 fps30 fps30 fps30 fps
Video bitrate800 Kbps2 Mbps4 Mbps10 Mbps

Video decoding recommendations

Device implementations must support dynamic video resolution and frame rate switching through the standard Android APIs within the same stream for all VP8, VP9, H.264, and H.265 codecs in real time and up to the maximum resolution supported by each codec on the device.

Implementations that support the Dolby Vision decoder must follow these guidelines:

  • Provide a Dolby Vision-capable extractor.
  • Properly display Dolby Vision content on the device screen or on a standard video output port (e.g., HDMI).
  • Set the track index of backward-compatible base-layer(s) (if present) to be the same as the combined Dolby Vision layer's track index.

Video streaming requirements

For video content that is streamed over HTTP or RTSP, there are additional requirements:

  • For 3GPP and MPEG-4 containers, the moov atom must precede any mdat atoms, but must succeed the ftyp atom.
  • For 3GPP, MPEG-4, and WebM containers, audio and video samples corresponding to the same time offset may be no more than 500 KB apart. To minimize this audio/video drift, consider interleaving audio and video in smaller chunk sizes.

Image support


Format / CodecEncoderDecoderDetailsSupported File Type(s) / Container Formats
BMP  BMP (.bmp)
GIF  GIF (.gif)
JPEGBase+progressiveJPEG (.jpg)
PNG PNG (.png)
WebP
(Android 4.0+)
(Lossless, Transparency, Android 4.2.1+)

(Android 4.0+)
(Lossless, Transparency, Android 4.2.1+)
 WebP (.webp)

Network protocols


The following network protocols are supported for audio and video playback:

  • RTSP (RTP, SDP)
  • HTTP/HTTPS progressive streaming
  • HTTP/HTTPS live streaming draft protocol:
    • MPEG-2 TS media files only
    • Protocol version 3 (Android 4.0 and above)
    • Protocol version 2 (Android 3.x)
    • Not supported before Android 3.0

Note: HTTPS is not supported before Android 3.1.



阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页