使用AudioTrack进行音频播放
2015-06-30 13:20
483 查看
Android学习笔记(3)——使用AudioTrack进行音频播放
该类的SDK文档是如下描述的:
android.media.AudioTrack.AudioTrack(intstreamType, int sampleRateInHz, int channelConfig, int audioFormat,int bufferSizeInBytes, int mode) throws
IllegalArgumentException
public AudioTrack (intstreamType, int sampleRateInHz, int channelConfig, int audioFormat,int bufferSizeInBytes, int mode)
Since:API Level3
Class constructor.
Parameters
streamType | the type of the audio stream. See STREAM_VOICE_CALL, STREAM_SYSTEM, STREAM_RING, STREAM_MUSICand STREAM_ALARM |
---|---|
sampleRateInHz | the sample rate expressed in Hertz. Examples of rates are (butnot limited to) 44100, 22050 and 11025. |
channelConfig | describes the configuration of the audio channels. SeeCHANNEL_OUT_MONOand CHANNEL_OUT_STEREO |
audioFormat | the format in which the audio data is represented. SeeENCODING_PCM_16BITand ENCODING_PCM_8BIT |
bufferSizeInBytes | the total size (in bytes) of the buffer where audio data isread from for playback. If using the AudioTrack in streaming mode,you can write data into this buffer in smaller chunks than thissize. If using the AudioTrack in static mode, this is the maximumsize of the sound that will be played for this instance. See getMinBufferSize(int, int, int)to determine the minimumrequired buffer size for the successful creation of an AudioTrackinstance in streaming mode. Using values smaller thangetMinBufferSize() will result in an initialization failure. |
mode | streaming or static buffer. See MODE_STATICand MODE_STREAM |
IllegalArgumentException |
---|
AudioTrackaudio = new AudioTrack(
AudioManager.STREAM_MUSIC, // 指定在流的类型
32000, // 设置音频数据的采样率 32k,如果是44.1k就是44100
AudioFormat.CHANNEL_OUT_STEREO, //设置输出声道为双声道立体声,而CHANNEL_OUT_MONO类型是单声道
AudioFormat.ENCODING_PCM_16BIT, //设置音频数据块是8位还是16位,这里设置为16位。好像现在绝大多数的音频都是16位的了
AudioTrack.MODE_STREAM //设置模式类型,在这里设置为流类型,另外一种MODE_STATIC貌似没有什么效果
);
audio.play(); // 启动音频设备,下面就可以真正开始音频数据的播放了
//打开mp3文件,读取数据,解码等操作省略 ...
byte[] buffer = newbuffer[4096];
intcount;
while(true)
{
// 最关键的是将解码后的数据,从缓冲区写入到AudioTrack对象中
audio.write(buffer, 0, 4096);
if(文件结束) break;
}
//最后别忘了关闭并释放资源
audio.stop();
audio.release();
相关文章推荐
- 【HDU 4609】3-idiots(FFT)
- iotop源码分析一
- 物联网系统的搭建(十)
- 物联网系统的搭建(九)
- 物联网系统的搭建(八)
- 物联网系统的搭建(七)
- 物联网系统的搭建(六)
- 物联网系统的搭建(五)
- 物联网系统的搭建(四)
- 物联网系统的搭建(三)
- 物联网系统的搭建(二)
- 物联网系统的搭建(一)
- UVa 10881 Piotr's Ants 蚂蚁
- Ubuntu 14.10 下进程实时IO监控iotop命令详解
- 【译】VisionMobile:2015 IOT大趋势(六)未来在此,开发者拥抱IoT
- 如何通过物联网获利
- HDU_4609_3-idiots
- Uva10881 - Piotr's Ants(蚂蚁)
- 【译】VisionMobile:2015 IOT大趋势(五)每人都是开发者
- 【译】VisionMobile:2015 IOT大趋势(四)消费者胜过CIO