• 18、多媒体的世界


    一、Android支持的媒体格式

    Network Protocols

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

    RTSP (RTP, SDP)

    HTTP progressive streaming

    HTTP live streaming draft protocol (Android 3.0 and above)

    Note: HTTPS is not supported at this time.

     

    Core Media Formats

     

    The table below describes the media format support built into the Android platform. Note that any given mobile device may provide support for additional formats or file types not listed in the table.

     

    Note: Media codecs that are not guaranteed to be available on all Android platform versions are accordingly noted in parentheses—for example "(Android 3.0+)".

     

    Table 1. Core media format and codec support.

    Type Format / Codec EncoderDecoderDetailsSupported File Type(s) / Container Formats

    Audio  AAC LC/LTP  • • Mono/Stereo content in any combination of standard bit rates up to 160 kbps and sampling rates from 8 to 48kHz  3GPP (.3gp), and MPEG-4 (.mp4, .m4a). ADTS raw AAC (.aac, decode only, ADIF not supported, Android 3.1+).

    HE-AACv1 (AAC+)     •

    HE-AACv2 (enhanced AAC+)    •

    AMR-NB • •  4.75 to 12.2 kbps sampled @ 8kHz   3GPP (.3gp)

    AMR-WB • •  9 rates from 6.60 kbit/s to 23.85 kbit/s sampled @ 16kHz3GPP (.3gp)

    FLAC   •

    (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

    MP3    • Mono/Stereo 8-320Kbps constant (CBR) or variable bit-rate (VBR) MP3 (.mp3)

    MIDI   • MIDI Type 0 and 1. DLS Version 1 and 2. XMF and Mobile XMF. Support for ringtone formats RTTTL/RTX, OTA, and iMelodyType 0 and 1 (.mid, .xmf, .mxmf). Also RTTTL/RTX (.rtttl, .rtx), OTA (.ota), and iMelody (.imy)

    Ogg Vorbis    •    Ogg (.ogg)

    PCM/WAVE     • 8- and 16-bit linear PCM (rates up to limit of hardware)WAVE (.wav)

    Image  JPEG • • Base+progressive JPEG (.jpg)

    GIF    •    GIF (.gif)

    PNG  • •    PNG (.png)

    BMP    •    BMP (.bmp)

    Video  H.263  • •    3GPP (.3gp) and MPEG-4 (.mp4)

    H.264 AVC •

    (Android 3.0+) • Baseline Profile (BP) 3GPP (.3gp) and MPEG-4 (.mp4). MPEG-TS (.ts, AAC audio only, not seekable, Android 3.0+)

    MPEG-4 SP    •   3GPP (.3gp)

    VP8    •

    (Android 2.3.3+)    WebM (.webm)

    Video Encoding Recommendations

     

    Table 2, below, lists examples of video encoding profiles and parameters that the Android media framework supports for playback. In addition to these encoding parameter recommendations, a device's available video recording profiles can be used as a proxy for media playback capabilities. These profiles can be inspected using the CamcorderProfile class, which is available since API level 8.

     

    Table 2. Examples of supported video encoding parameters.

      Lower quality  Higher quality

    Video codec H.264 Baseline ProfileH.264 Baseline Profile

    Video resolution 176 x 144 px480 x 360 px

    Video frame rate 12 fps 30 fps

    Video bitrate  56 Kbps500 Kbps

    Audio codec AAC-LC AAC-LC

    Audio channels 1 (mono)  2 (stereo)

    Audio bitrate  24 Kbps128 Kbps

    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.

        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.

     

    二、使用MediaPlayer加载资源

     1 1, 资源文件  , create
     2 MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
     3 mediaPlayer.start(); // no need to call prepare(); create() does that for you
     4 
     5 2,本地文件 , setDataSource()
     6 Uri myUri = ....; // initialize Uri here
     7 MediaPlayer mediaPlayer = new MediaPlayer();
     8 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
     9 mediaPlayer.setDataSource(getApplicationContext(), myUri);
    10 mediaPlayer.prepare();
    11 mediaPlayer.start();
    12 
    13 3,网络文件: setDataSource()
    14 String url = "http://........"; // your URL here
    15 MediaPlayer mediaPlayer = new MediaPlayer();
    16 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    17 mediaPlayer.setDataSource(url);
    18 mediaPlayer.prepare(); // might take long! (for buffering, etc)
    19 mediaPlayer.start();
    20 
    21 一般不要直接用create  , 为何?多点几次试试?

    三、MediaPlayer控制状态图

    (1)当MediaPlayer对象刚new或者调用了reset()之后,就处于Idie状态

    release()之后就处于end状态,这两个状态之间的生命周期如下。

    (2)new和reset()之后都是idle状态,有区别么?

    MediaPlayer 有一个错误监听机制 OnErrorListener.onError() 

        如果在调用方法( getCurrentPosition(), getDuration(), getVideoHeight(), getVideoWidth(), setAudioStreamType(int), setLooping(boolean), setVolume(float, float), pause(), start(), stop(), seekTo(int), prepare() or prepareAsync()) 的时候,如果执行正确 

         create idle状态不会触发OnErrorListener.onError()  ,并且状态不会变化

    但reset() idle 会触发 OnErrorListener.onError() ,并且状态会改为 Error。

         因此Mediaplayer不再用的时候,及时调用release(),释放内部播放引擎和MediaPlayer对象的关联。

     

    (3)引入播放控制的侦听机制

    我们常常会遇到各种复杂问题导致播放的时候出错 ,比如:

    1,播放格式不允许 ,

    2,文件格式损坏,

    3,视频分辨率过高,

    4,流超时  等等

    为了有效的帮助我们监测并且处理这些错误,当然需要一套错误监听机制 

     setOnErrorListener(android.media.MediaPlayer.OnErrorListener)

    a一旦出错,状态就进入了error;

    b对于error状态如果要重新使用,就调用reset()方法进入idle状态;

    c商业应用程序都需要注册errorlistenter 来处理错误;

    d无效状态下调用prepare() or prepareAsync()方法会出现IllegalStateException异常;

    (4)调用setDataSource(..)方法会将MediaPlayer对象又Idle状态转为Initialized状态

    a只要是Idle之外的所有状态调用setDataSource()就会出现 IllegalStateException异常.

    b建议调用setDataSource()方法的时候捕获IllegalArgumentException and IOException.

     

    (5)MediaPlayer必须先要进入prepared状态才可以start

    a同步prepare()

    b异步prepareAsync()+

    setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener).

    c提醒,preparing是一个机器短暂的状态

    d在prepared状态,可以调用相应方法调整Volume,screenOnWhilePalying,Looping等属性.

     

    (6)调用start进入started状态,可以调用isPlaying()判断是否是started状态

    a播放过程中可以用 setOnBufferingUpdateListener(OnBufferingUpdateListener)监听播放进度

    b正在播放中调用start()无效果.

     

    (7)调用stop()可以让started , paused , prepared 或者 PlaybackCOmpleted状态都进入到stopped状态

    a、一旦stopped ,流程又需要重来

    b、stopped状态调用stop()无效果

     

    (8)通过seekTo(int)调整播放进度

    【调用后同样需要一些时间才能真正执行结束】

    用setOnSeekCompleteListener(OnSeekCompleteListener).侦听;

    Parepared , Paused , PlaybackCompleted状态都可以调用seekTo(int);

     

    (9)播放到达流终点 ,播放停止

    a 如果设定了自动循环,则状态会自动改为started

    b 如果setLooping(false),则监听

      setOnCompletionListener(OnCompletionListener)

    c PlaybackCompleted状态,直接调用start()可以重新播放.

     

    四、使用异步准备prepareAsync(MediaPlayer)

    prepare 还是要花时间的,一般情况下比较短 ,但哪怕是0.5s , 那也不短

    因为他有时候会包含识别和解码媒体文件 ,这就是耗时工作 。

    因此:不要在UI线程直接调用prepare(),那很容易引起ANR ,而是使用如下办法:

    1,开一个线程 , 准备好后通知UI线程(handler)

    2,使用prepareAsync() 异步准备

     五、MediaPlayer的释放

    MediaPlayer会占用大量的关联资源 。

    因此不用了要及时释放 ,哪怕是突然来了个电话,你的Activity onStop了,也要释放掉 。

    释放方式:

    mediaPlayer.release();

    mediaPlayer = null;

    六、使用后台服务(MediaPlayer)

     1 public class MyService extends Service implements
     2  MediaPlayer.OnErrorListener {
     3     MediaPlayer mMediaPlayer;
     4 
     5     public void initMediaPlayer() {
     6         // ...initialize the MediaPlayer here...
     7         mMediaPlayer.setOnErrorListener(this);
     8     }
     9 
    10     @Override
    11     public boolean onError(MediaPlayer mp, int what, int extra) {
    12         // ... react appropriately ...
    13         // The MediaPlayer has moved to the Error state, must be reset!
    14     }
    15 }

    七、使用wake lock(MediaPlayer)

    1,

    mMediaPlayer = new MediaPlayer();

    // ... other initialization here ...

    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

     

    2,如果你用网络了

    WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))

        .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

     

    wifiLock.acquire();

    不用了,要释放锁定

    wifiLock.release();

     

    八、运行前台服务(MediaPlayer)

     1 我们知道,后台服务可能会被系统自动释放掉 ,这不是我们想看到的 
     2 String songName;
     3 // assign the song name to songName
     4 PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
     5                 new Intent(getApplicationContext(), MainActivity.class),
     6                 PendingIntent.FLAG_UPDATE_CURRENT);
     7 Notification notification = new Notification();
     8 notification.tickerText = text;
     9 notification.icon = R.drawable.play0;
    10 notification.flags |= Notification.FLAG_ONGOING_EVENT;
    11 notification.setLatestEventInfo(getApplicationContext(), "MusicPlayerSample",
    12                 "Playing: " + songName, pi);
    13 startForeground(NOTIFICATION_ID, notification);
    14 
    15 ------不再用了,停止服务--------
    16 stopForeground(true);

    九、操作声音焦点(MediaPlayer)

    比如电话铃声想起 , 控制你当前播放声音减小或者停止

     

    十、Case:音频播放的HelloWorld

    Case扩展1,如何加入音频的控制:

    Case扩展2:SDCard Raw文件播放:

    Case扩展3:网络文件播放:

    Case扩展4:自定义音频文件格式:

    Case扩展5:商业中使用Service播放音频文件:

     

    十一、Case:视频播放的Helloworld

    Case扩展6:SurfaceView的应用:

    Case扩展7: 从网络播放视频:

    十二、录制声音和视频

    使用Intent录制;

    使用Media Recorder录制;

    十三、照相及录像

    (1)使用Intent拍照,录像

    (2)控制拍照和录像

    监测设置; 监测自动对焦;使用预览;生成图片;读取和写入图片EXIF信息;

     

    十四、语音识别

     

    十五、Media Store

  • 相关阅读:
    Codeforces Round #407 (Div. 2)A B C 水 暴力 最大子序列和
    Codeforces Round #358 (Div. 2) A B C 水 水 dfs序+dp
    51nod 1225 数学
    HDU 4584 splay
    bzoj 1588 平衡树 splay
    HDU 4722 数位dp
    Kubernetes 自动伸缩 auto-scaling
    转发一篇能看懂的关于ingress的说明
    Http 安全检测
    mdadm 软RAID
  • 原文地址:https://www.cnblogs.com/androidsj/p/3974347.html
Copyright © 2020-2023  润新知