1.使用System Sound Services播放音效
System Sound Services是最简单、也比较底层的音效播放服务,使用System Sound Services只适合播放一些很小的提示或者警告音频。
它存在如下限制:
(1)声音长度不能超过30秒;
(2)声音文件必须是PCM或者IMA4(IMA/ADPCM)格式;
(3)打包成.caf、.aif、.wav的文件;
(4)不能控制播放的进度;
(5)调用方法后立即播放声音;
(6)没有循环播放和立体声控制。
示例:一个按钮控制一个音效,需要AudioToolbox框架支持。
ViewController.m
#import "ViewController.h"
#import <AudioToolbox/AudioToolbox.h>
@interface ViewController ()
@end
void completionCallback(SystemSoundID mySSID)
{
AudioServicesPlaySystemSound(mySSID);
}
SystemSoundID crash;
@implementation ViewController
- (void)viewDidLoad
{
[superviewDidLoad];
//需要播放的音频文件
NSURL *crashUrl = [[NSBundlemainBundle]URLForResource:@"hello"withExtension:@"wav"];
//加载音频文件
AudioServicesCreateSystemSoundID((__bridgeCFURLRef)crashUrl, &crash);
//为crash播放完成绑定回调函数
AudioServicesAddSystemSoundCompletion(crash,NULL, NULL, (void *)completionCallback,NULL);
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)play:(id)sender {
//播放crash代表的音频
AudioServicesPlaySystemSound(crash);
//播放crash代表的音频,并控制设备震动
//AudioServicesPlayAlertSound(crash);
}
@end
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
- (IBAction)play:(id)sender;
@end
2.使用AVAudioPlayer播放音乐
AVAudioPlayer是一个属于AVFoudationframework的类,它的作用类似于一个功能强大的播放器。AVAudioPlayer支持广泛的音频格式,主要是以下几种:
(1)AAC
(2)AMR(Adaptive Multi-Rate,一种语音格式)
(3)ALAC(Apple Lossless Audio Codec)
(4)iLBC(internet Low Bitrace Codec)
(5)IMA4(IMA/ADPCM)
(6)linearPCM(uncompressed)
(7)μ-law和a-low
(8)MP3(MPEG-Laudio Layer3)
示例:需要AVFoundation框架支持
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
AVAudioPlayer *audioPlayer;
CGFloat durationTime;
NSTimer *timer;
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//获取要播放音乐的URL
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"Apologize大提琴版伴奏" withExtension:@"mp3"];
//创建AVAudioPlayer对象
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
NSString *msg = [NSString stringWithFormat:@"音频文件声道数:%d\n音频文件持续时间%g",audioPlayer.numberOfChannels,audioPlayer.duration];
self.show.text = msg;
durationTime = audioPlayer.duration;
//将循环次数设为-1,用于指定该音频文件循环播放
//audioPlayer.numberOfLoops = -1;
//为AVAudioPlayer设置代理,监听它的播放事件
audioPlayer.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//播放完成后自动调用该方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if(player == audioPlayer && flag)
{
NSLog(@"播放完成");
[self.playBtn setTitle:@"Play" forState:UIControlStateNormal];
}
}
- (void) audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
if(player == audioPlayer)
{
NSLog(@"被中断!");
}
}
- (IBAction)play:(id)sender {
//如果当前正在播放
if(audioPlayer.playing)
{
//暂停播放
[audioPlayer pause];
[self.playBtn setTitle:@"Pause" forState:UIControlStateNormal];
}
else
{
[audioPlayer play];
[self.playBtn setTitle:@"Play" forState:UIControlStateNormal];
}
//如果timer为nil,则执行如下方法
if(timer == nil)
{
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProg) userInfo:nil repeats:YES];
}
}
- (IBAction)stop:(id)sender {
//停止播放音频
[audioPlayer stop];
audioPlayer.currentTime = 0;
[timer invalidate];
timer = nil;
}
- (void) updateProg
{
self.prog.progress = audioPlayer.currentTime / durationTime;
}
@end
ViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController<AVAudioPlayerDelegate>
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UIButton *stopBtn;
@property (weak, nonatomic) IBOutlet UIProgressView *prog;
@property (weak, nonatomic) IBOutlet UILabel *show;
- (IBAction)play:(id)sender;
- (IBAction)stop:(id)sender;
@end
运行结果图:
3.使用MPMoviePlayerController播放视频
MPMoviePlayerController与MPMusicPlayerController相似,它们都是一个简单的播放器,而且都实现了MPMediaPlayer协议,因此它们有相似的play、stop、pause等播放方法。
示例:需要MediaPlayer框架支持。
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
MPMoviePlayerController *moviePlayer;
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//创建本地URL(也可以创建基于网络的URL)
NSURL *movieUrl = [[NSBundle mainBundle] URLForResource:@"m" withExtension:@"mp4"];
//使用指定URL创建MPMoviePlayerController
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieUrl];
//设置播放器的控制条风格
moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
//设置播放器缩放模式
moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[moviePlayer.view setFrame:CGRectMake(20, 10, 250, 340)];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)play:(id)sender {
//播放视频
[moviePlayer prepareToPlay];
[self.movieView addSubview:moviePlayer.view];
}
@end
ViewController.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController : UIViewController
- (IBAction)play:(id)sender;
@property (weak, nonatomic) IBOutlet UIView *movieView;
@end
运行结果图: