iOS开发之多媒体播放

iOS sdk中提供了很多方便的方法来播放多媒体。本文将利用这些SDK做一个demo,来讲述一下如何使用它们来播放音频文件。

[b]AudioToolbox framework[/b]

使用AudioToolbox framework。这个框架可以将比较短的声音注册到 system sound服务上。被注册到system sound服务上的声音称之为 system sounds。它必须满足下面几个条件。

1、播放的时间不能超过30秒

2、数据必须是 PCM或者IMA4流格式

3、必须被打包成下面三个格式之一:Core Audio Format (.caf), Waveform audio (.wav),或者 Audio Interchange File (.aiff)

声音文件必须放到设备的本地文件夹下面。通过AudioServicesCreateSystemSoundID方法注册这个声音文件,AudioServicesCreateSystemSoundID需要声音文件的url的CFURLRef对象。看下面注册代码:

<div class="cnblogs_code"><pre><span style="color: #0000ff;">#import</span><span style="color: #000000;"> </span><span style="color: #000000;"><</span><span style="color: #000000;">AudioToolbox</span><span style="color: #000000;">/</span><span style="color: #000000;">AudioToolbox.h</span><span style="color: #000000;">></span><span style="color: #000000;">
</span><span style="color: #0000ff;">@interface</span><span style="color: #000000;"> MediaPlayerViewController : UIViewController
{
IBOutlet UIButton </span><span style="color: #000000;">*</span><span style="color: #000000;">audioButton;
SystemSoundID shortSound;
}</span></pre>
<div class="cnblogs_code"><pre><span style="color: #000000;">-</span><span style="color: #000000;"> (</span><span style="color: #0000ff;">id</span><span style="color: #000000;">)init
{
self </span><span style="color: #000000;">=</span><span style="color: #000000;"> [super initWithNibName:</span><span style="color: #800000;">@"</span><span style="color: #800000;">MediaPlayerViewController</span><span style="color: #800000;">"</span><span style="color: #000000;"> bundle:nil];
</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (self) {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Get the full path of Sound12.aif</span><span style="color: #008000;">
</span><span style="color: #000000;"> NSString </span><span style="color: #000000;">*</span><span style="color: #000000;">soundPath </span><span style="color: #000000;">=</span><span style="color: #000000;"> [[NSBundle mainBundle] pathForResource:</span><span style="color: #800000;">@"</span><span style="color: #800000;">Sound12</span><span style="color: #800000;">"</span><span style="color: #000000;">
ofType:</span><span style="color: #800000;">@"</span><span style="color: #800000;">aif</span><span style="color: #800000;">"</span><span style="color: #000000;">];
</span><span style="color: #008000;">//</span><span style="color: #008000;"> If this file is actually in the bundle...</span><span style="color: #008000;">
</span><span style="color: #000000;"> </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (soundPath) {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Create a file URL with this path</span><span style="color: #008000;">
</span><span style="color: #000000;"> NSURL </span><span style="color: #000000;">*</span><span style="color: #000000;">soundURL </span><span style="color: #000000;">=</span><span style="color: #000000;"> [NSURL fileURLWithPath:soundPath];

</span><span style="color: #008000;">//</span><span style="color: #008000;"> Register sound file located at that URL as a system sound</span><span style="color: #008000;">
</span><span style="color: #000000;"> OSStatus err </span><span style="color: #000000;">=</span><span style="color: #000000;"> AudioServicesCreateSystemSoundID((CFURLRef)soundURL,
</span><span style="color: #000000;">&</span><span style="color: #000000;">shortSound);
</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (err </span><span style="color: #000000;">!=</span><span style="color: #000000;"> kAudioServicesNoError)
NSLog(</span><span style="color: #800000;">@"</span><span style="color: #800000;">Could not load %@, error code: %d</span><span style="color: #800000;">"</span><span style="color: #000000;">, soundURL, err);
}
}
</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> self;
}</span></pre>
这样就可以使用下面代码播放声音了:

<div class="cnblogs_code"><pre><span style="color: #000000;">-</span><span style="color: #000000;"> (IBAction)playShortSound:(</span><span style="color: #0000ff;">id</span><span style="color: #000000;">)sender
{
AudioServicesPlaySystemSound(shortSound);
}</span></pre>
使用下面代码,还加一个震动的效果:

<div class="cnblogs_code"><pre><span style="color: #000000;">-</span><span style="color: #000000;"> (IBAction)playShortSound:(</span><span style="color: #0000ff;">id</span><span style="color: #000000;">)sender
{
AudioServicesPlaySystemSound(shortSound);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}</span></pre>
[b]AVFoundation framework[/b]

对于压缩过Audio文件,或者超过30秒的音频文件,可以使用AVAudioPlayer类。这个类定义在AVFoundation framework中。

下面我们使用这个类播放一个mp3的音频文件。首先要引入AVFoundation framework,然后MediaPlayerViewController.h中添加下面代码:

<div class="cnblogs_code"><pre><span style="color: #0000ff;">#import</span><span style="color: #000000;"> </span><span style="color: #000000;"><</span><span style="color: #000000;">AVFoundation</span><span style="color: #000000;">/</span><span style="color: #000000;">AVFoundation.h</span><span style="color: #000000;">></span><span style="color: #000000;">
</span><span style="color: #0000ff;">@interface</span><span style="color: #000000;"> MediaPlayerViewController : UIViewController </span><span style="color: #000000;"><</span><span style="color: #000000;">AVAudioPlayerDelegate</span><span style="color: #000000;">></span><span style="color: #000000;">
{
IBOutlet UIButton </span><span style="color: #000000;">*</span><span style="color: #000000;">audioButton;
SystemSoundID shortSound;
AVAudioPlayer </span><span style="color: #000000;">*</span><span style="color: #000000;">audioPlayer;</span></pre>
AVAudioPlayer类也是需要知道音频文件的路径,使用下面代码创建一个AVAudioPlayer实例:

<div class="cnblogs_code"><pre><span style="color: #000000;">-</span><span style="color: #000000;"> (</span><span style="color: #0000ff;">id</span><span style="color: #000000;">)init
{
self </span><span style="color: #000000;">=</span><span style="color: #000000;"> [super initWithNibName:</span><span style="color: #800000;">@"</span><span style="color: #800000;">MediaPlayerViewController</span><span style="color: #800000;">"</span><span style="color: #000000;"> bundle:nil];

</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (self) {

NSString </span><span style="color: #000000;">*</span><span style="color: #000000;">musicPath </span><span style="color: #000000;">=</span><span style="color: #000000;"> [[NSBundle mainBundle] pathForResource:</span><span style="color: #800000;">@"</span><span style="color: #800000;">Music</span><span style="color: #800000;">"</span><span style="color: #000000;">
ofType:</span><span style="color: #800000;">@"</span><span style="color: #800000;">mp3</span><span style="color: #800000;">"</span><span style="color: #000000;">];
</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (musicPath) {
NSURL </span><span style="color: #000000;">*</span><span style="color: #000000;">musicURL </span><span style="color: #000000;">=</span><span style="color: #000000;"> [NSURL fileURLWithPath:musicPath];
audioPlayer </span><span style="color: #000000;">=</span><span style="color: #000000;"> [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL
error:nil];
[audioPlayer setDelegate:self];
}
NSString </span><span style="color: #000000;">*</span><span style="color: #000000;">soundPath </span><span style="color: #000000;">=</span><span style="color: #000000;"> [[NSBundle mainBundle] pathForResource:</span><span style="color: #800000;">@"</span><span style="color: #800000;">Sound12</span><span style="color: #800000;">"</span><span style="color: #000000;">
ofType:</span><span style="color: #800000;">@"</span><span style="color: #800000;">aif</span><span style="color: #800000;">"</span><span style="color: #000000;">];</span></pre>
我们可以在一个button的点击事件中开始播放这个mp3文件,如:

<div class="cnblogs_code"><pre><span style="color: #000000;">-</span><span style="color: #000000;"> (IBAction)playAudioFile:(</span><span style="color: #0000ff;">id</span><span style="color: #000000;">)sender
{
</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> ([audioPlayer isPlaying]) {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Stop playing audio and change text of button</span><span style="color: #008000;">
</span><span style="color: #000000;"> [audioPlayer stop];
[sender setTitle:</span><span style="color: #800000;">@"</span><span style="color: #800000;">Play Audio File</span><span style="color: #800000;">"</span><span style="color: #000000;">
forState:UIControlStateNormal];
}
</span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {
</span><span style="color: #008000;">//</span><span style="color: #008000;"> Start playing audio and change text of button so
</span><span style="color: #008000;">//</span><span style="color: #008000;"> user can tap to stop playback</span><span style="color: #008000;">
</span><span style="color: #000000;"> [audioPlayer play];
[sender setTitle:</span><span style="color: #800000;">@"</span><span style="color: #800000;">Stop Audio File</span><span style="color: #800000;">"</span><span style="color: #000000;">
forState:UIControlStateNormal];
}
}</span></pre>
这样运行我们的程序,就可以播放音乐了。

这个类对应的<span style="color: #000000;"><span style="font-family: Courier New;">AVAudioPlayerDelegate</span></span>有两个委托方法。一个是 audioPlayerDidFinishPlaying:successfully: 当音频播放完成之后触发。当播放完成之后,可以将播放按钮的文本重新回设置成:Play Audio File

<div class="cnblogs_code"><pre><span style="color: #000000;">-</span><span style="color: #000000;"> (</span><span style="color: #0000ff;">void</span><span style="color: #000000;">)audioPlayerDidFinishPlaying:(AVAudioPlayer </span><span style="color: #000000;">*</span><span style="color: #000000;">)player
successfully:(BOOL)flag
{
[audioButton setTitle:</span><span style="color: #800000;">@"</span><span style="color: #800000;">Play Audio File</span><span style="color: #800000;">"</span><span style="color: #000000;">
forState:UIControlStateNormal];
}</span></pre>
另一个是audioPlayerEndInterruption:,当程序被应用外部打断之后,重新回到应用程序的时候触发。在这里当回到此应用程序的时候,继续播放音乐。

<div class="cnblogs_code"><pre><span style="color: #000000;">-</span><span style="color: #000000;"> (</span><span style="color: #0000ff;">void</span><span style="color: #000000;">)audioPlayerEndInterruption:(AVAudioPlayer </span><span style="color: #000000;">*</span><span style="color: #000000;">)player
{
[audioPlayer play];
}</span></pre>
[b]MediaPlayer framework[/b]

播放电影文件:

iOS sdk中可以使用MPMoviePlayerController来播放电影文件。但是在iOS设备上播放电影文件有严格的格式要求,只能播放下面两个格式的电影文件。

? H.264 (Baseline Profile Level 3.0)<br>? MPEG-4 Part 2 video (Simple Profile)

幸运的是你可以先使用iTunes将文件转换成上面两个格式。<br>MPMoviePlayerController还可以播放互联网上的视频文件。但是建议你先将视频文件下载到本地,然后播放。如果你不这样做,iOS可能会拒绝播放很大的视频文件。

这个类定义在MediaPlayer framework中。在你的应用程序中,先添加这个引用,然后修改<span style="font-family: Courier New;">MediaPlayerViewController.</span>h文件。

<div class="cnblogs_code"><pre><span style="color: #0000ff;">#import</span><span style="color: #000000;"> </span><span style="color: #000000;"><</span><span style="color: #000000;">MediaPlayer</span><span style="color: #000000;">/</span><span style="color: #000000;">MediaPlayer.h</span><span style="color: #000000;">></span><span style="color: #000000;">
</span><span style="color: #0000ff;">@interface</span><span style="color: #000000;"> MediaPlayerViewController : UIViewController </span><span style="color: #000000;"><</span><span style="color: #000000;">AVAudioPlayerDelegate</span><span style="color: #000000;">></span><span style="color: #000000;">
{
MPMoviePlayerController </span><span style="color: #000000;">*</span><span style="color: #000000;">moviePlayer;</span></pre>
下面我们使用这个类来播放一个.m4v 格式的视频文件。与前面的类似,需要一个url路径。

<div class="cnblogs_code"><pre><span style="color: #000000;">-</span><span style="color: #000000;"> (</span><span style="color: #0000ff;">id</span><span style="color: #000000;">)init
{
self </span><span style="color: #000000;">=</span><span style="color: #000000;"> [super initWithNibName:</span><span style="color: #800000;">@"</span><span style="color: #800000;">MediaPlayerViewController</span><span style="color: #800000;">"</span><span style="color: #000000;"> bundle:nil];
</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (self) {

NSString </span><span style="color: #000000;">*</span><span style="color: #000000;">moviePath </span><span style="color: #000000;">=</span><span style="color: #000000;"> [[NSBundle mainBundle] pathForResource:</span><span style="color: #800000;">@"</span><span style="color: #800000;">Layers</span><span style="color: #800000;">"</span><span style="color: #000000;">
ofType:</span><span style="color: #800000;">@"</span><span style="color: #800000;">m4v</span><span style="color: #800000;">"</span><span style="color: #000000;">];
</span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (moviePath) {
NSURL </span><span style="color: #000000;">*</span><span style="color: #000000;">movieURL </span><span style="color: #000000;">=</span><span style="color: #000000;"> [NSURL fileURLWithPath:moviePath];
moviePlayer </span><span style="color: #000000;">=</span><span style="color: #000000;"> [[MPMoviePlayerController alloc]
initWithContentURL:movieURL];
}</span></pre>
MPMoviePlayerController有一个视图来展示播放器控件,我们在viewDidLoad方法中,将这个播放器展示出来。

<div class="cnblogs_code"><pre><span style="color: #000000;">-</span><span style="color: #000000;"> (</span><span style="color: #0000ff;">void</span><span style="color: #000000;">)viewDidLoad
{
[[self view] addSubview:[moviePlayer view]];
</span><span style="color: #0000ff;">float</span><span style="color: #000000;"> halfHeight </span><span style="color: #000000;">=</span><span style="color: #000000;"> [[self view] bounds].size.height </span><span style="color: #000000;">/</span><span style="color: #000000;"> </span><span style="color: #800080;">2.0</span><span style="color: #000000;">;
</span><span style="color: #0000ff;">float</span><span style="color: #000000;"> width </span><span style="color: #000000;">=</span><span style="color: #000000;"> [[self view] bounds].size.width;
[[moviePlayer view] setFrame:CGRectMake(</span><span style="color: #800080;">0</span><span style="color: #000000;">, halfHeight, width, halfHeight)];
}</span></pre>
还有一个MPMoviePlayerViewController类,用于全屏播放视频文件,用法和MPMoviePlayerController一样。

<div class="cnblogs_code"><pre><span style="color: #000000;">MPMoviePlayerViewController </span><span style="color: #000000;">*</span><span style="color: #000000;">playerViewController </span><span style="color: #000000;">=</span><span style="color: #000000;">
[[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
[viewController presentMoviePlayerViewControllerAnimated:playerViewController];</span></pre>
我们在听音乐的时候,可以用iphone做其他的事情,这个时候需要播放器在后台也能运行,我们只需要在应用程序中做个简单的设置就行了。

1、在Info property list中加一个 Required background modes节点,它是一个数组,将第一项设置成设置App plays audio。

2、在播放mp3的代码中加入下面代码:

<div class="cnblogs_code"><pre><span style="color: #000000;"> </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (musicPath) {
NSURL </span><span style="color: #000000;">*</span><span style="color: #000000;">musicURL </span><span style="color: #000000;">=</span><span style="color: #000000;"> [NSURL fileURLWithPath:musicPath];
[[AVAudioSession sharedInstance]
setCategory:AVAudioSessionCategoryPlayback error:nil];
audioPlayer </span><span style="color: #000000;">=</span><span style="color: #000000;"> [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL
error:nil];
[audioPlayer setDelegate:self];
}</span></pre>
在后台运行的播放音乐的功能在模拟器中看不出来,只有在真机上看效果。

<img alt="" src="http://hi.csdn.net/attachment/201107/24/0_1311506457iPg4.gif">

[b]总结:[/b]本文通过例子详细讲解了iOS sdk中用于播放音频文件的类,文章后面有本文的代码提供下载。

[b]代码:[url=http://files.cnblogs.com/zhuqil/MediaPlayer.zip]点击打开链接[/url][/b]
package com.demo.pr5; import java.io.File; import java.util.Vector; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class MyFileActivity extends Activity { // 支持的媒体格式 private final String[]FILE_MapTable = { ".3gp",".mov",".avi", ".rmvb", ".wmv", ".mp3", ".mp4" }; private Vector<String> items = null; // items:存放显示的名称 private Vector<String> paths = null; // paths:存放文件路径 private Vector<String> sizes = null; // sizes:文件大小 private String rootPath = "/mnt/sdcard"; //起始文件夹 private EditText pathEditText; // 路径 private Button queryButton; //查询按钮 private ListView fileListView;//文件列表 @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); this.setTitle("多媒体文件浏览"); setContentView(R.layout.myfile); //从myfile.xml找到对应的元素 pathEditText = (EditText) findViewById(R.id.path_edit); queryButton = (Button) findViewById(R.id.qry_button); fileListView= (ListView) findViewById(R.id.file_listview); //查询按钮事件 queryButton.setOnClickListener( new Button.OnClickListener() { public void onClick(View arg0) { File file = new File(pathEditText.getText().toString()); if (file.exists()) { if (file.isFile()) { //如果是媒体文件直接打开播放 openFile(pathEditText.getText().toString()); } else { //如果是目录打开目录下文件 getFileDir(pathEditText.getText().toString()); } } else { Toast.makeText(MyFileActivity.this, "找不到该位置,请确定位置是否正确!", Toast.LENGTH_SHORT).show(); } } }); //设置ListItem被点击时要做的动作 fileListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { fileOrDir(paths.get(position)); } }); //打开默认文件夹 getFileDir(rootPath); } /** * 重写返回键功能:返回上一级文件夹 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // 是否触发按键为back键 if (keyCode == KeyEvent.KEYCODE_BACK) { pathEditText = (EditText) findViewById(R.id.path_edit); File file = new File(pathEditText.getText().toString()); if (rootPath.equals(pathEditText.getText().toString().trim())) { return super.onKeyDown(keyCode, event); } else { getFileDir(file.getParent()); return true; } //如果不是back键正常响应 } else { return super.onKeyDown(keyCode, event); } } /** * 处理文件或者目录的方法 */ private void fileOrDir(String path) { File file = new File(path); if (file.isDirectory()) { getFileDir(file.getPath()); } else { openFile(path); } } /** * 取得文件结构的方法 */ private void getFileDir(String filePath) { /* 设置目前所在路径 */ pathEditText.setText(filePath); items = new Vector<String>(); paths = new Vector<String>(); sizes = new Vector<String>(); File f = new File(filePath); File[] files = f.listFiles(); if (files != null) { /* 将所有文件添加ArrayList中 */ for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { items.add(files[i].getName()); paths.add(files[i].getPath()); sizes.add(""); } } for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { String fileName = files[i].getName(); int index = fileName.lastIndexOf("."); if (index > 0) { String endName = fileName.substring(index, fileName.length()).toLowerCase(); String type = null; for (int x = 0; x < FILE_MapTable.length; x++) { // 支持的格式,才会在文件浏览器中显示 if (endName.equals(FILE_MapTable[x])) { type = FILE_MapTable[x]; break; } } if (type != null) { items.add(files[i].getName()); paths.add(files[i].getPath()); sizes.add(files[i].length()+""); } } } } } /* 使用自定义的FileListAdapter来将数据传入ListView */ fileListView.setAdapter(new FileListAdapter(this, items)); } /** * 打开媒体文件 * @param f */ private void openFile(String path) { //打开媒体播放器 Intent intent = new Intent(MyFileActivity.this, MediaPlayerActivity.class); intent.putExtra("path",path); startActivity(intent); finish(); } /** *ListView列表适配器 */ class FileListAdapter extends BaseAdapter { private Vector<String> items = null; // items:存放显示的名称 private MyFileActivity myFile; public FileListAdapter(MyFileActivity myFile, Vector<String> items) { this.items=items; this.myFile=myFile; } @Override public int getCount() { // TODO Auto-generated method stub return items.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return items.elementAt(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return items.size(); } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if(convertView==null) { //加载列表项布局file_item.xml convertView = myFile.getLayoutInflater() .inflate(R.layout.file_item, null); } //文件名称 TextView name = (TextView) convertView.findViewById(R.id.name); //媒体文件类型 ImageView music=(ImageView)convertView.findViewById(R.id.music); //文件夹类型 ImageView folder=(ImageView)convertView.findViewById(R.id.folder); name.setText(items.elementAt(position)); if(sizes.elementAt(position).equals("")) { //隐藏媒体图标,显示文件夹图标 music.setVisibility(View.GONE); folder.setVisibility(View.VISIBLE); }else { //隐藏文件夹图标,显示媒体图标 folder.setVisibility(View.GONE); music.setVisibility(View.VISIBLE); } return convertView; } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值