Android 多媒体开发-音频

来源:互联网 发布:淘宝宝贝上下架时间怎么设置 编辑:程序博客网 时间:2024/05/21 09:48

  如今,任何名副其实的智能手机都具有音频播放功能。当然,基于android的设备也不例外,它允许你建立音乐播放器,音频书籍,播客或任何围绕音频播放的其他应用类程序。本次将讨论Android在格式和编解码器支持方面的功能同时还将构建几个不同的播放程序。

  音频播放

  Android支持多种用于播放的音频文件格式和编解码器(同时也支持录音)

  • AAC
  • MP3
  • AMR
  • Ogg
  • PCM

   具体的格式介绍可以自行查阅资料

   通过意图使用系统内置的播放器

    通过意图来促发播放制定的文件,使用android.content.Intent.ACTION_VIEW意图的数据设置为一个音频文件的URI,并指定其MIME类型,这样Android就可以挑选设当的应用程序播放。

      Intent intent=new Intent(android.content.Intent.ACTION_VIEW);

      intent.setDataAndType(audioFileUri,"audio/mp3");

      startActivity(intent);

      下面是一个完整的示例,

     

import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

  1. /**
  2. * 本示例演示如何利用Android自带的Music来播放程序
  3. * 和Camera一样,可以通过Intent来启动它。
  4. * 我们需要指定一个ACTION_VIEW的Action
  5. * 同时一个Uri来指定我们要播放文件的路径
  6. * 最后指定一个MIME类型,指定所要播放的文件类型
  7. * 每种文件类型对应的都有一个MIME,他一般是类似于audio/mp3格式
  8. * 前部分是一个较大的类型,后面是更具体的类型
  9. *
  10. * 同样的,对于Audio类型的多媒体,系统存储在MediaStore.Audio中
  11. * 包括Media,Album,Genre等信息体
  12. *
  13. * 本文将以列表的形式列出所有的Album信息,供用户选择
  14. * 当用户选择某个Album时,系统将打开这个ALbum下的所有Audio
  15. * @author Administrator
  16. *
  17. */

 

    在触发播放音频之前,活动将监听是否按下一个按钮。由于活动实现OnClickListener,因此它可以响应该事件。

public class IntentAudioPlayer extends Activity implements OnClickListener {

 Button playButton;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  playButton = (Button) this.findViewById(R.id.Button01);
  playButton.setOnClickListener(this);
 }

 public void onClick(View v) {
  Intent intent = new Intent(android.content.Intent.ACTION_VIEW);

  File sdcard = Environment.getExternalStorageDirectory();
  File audioFile = new File(sdcard.getPath()
    + "/Music/goodmorningandroid.mp3");

  intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
  startActivity(intent);
 }
}

      以下是布局文件:

      <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button android:text="Play Audio" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

   关于这一部分,还有一篇进阶的文章大家可以看看:http://blog.csdn.net/chenjie19891104/article/details/6330383