AudioToolbox framework
1、
2、数据必须是 PCM或者IMA4流格式, mp3也可以
3、必须被打包成下面三个格式之一:Core Audio Format (.caf), Waveform audio (.wav),
- (void)playSoundWithName:(NSString *)name type:(NSString *)type
{
}
AVFoundation framework
#import <</span>AVFoundation/AVFoundation.h>
@interface MediaPlayerViewController : UIViewController <</span>AVAudioPlayerDelegate>
{
IBOutlet UIButton *audioButton;
SystemSoundID shortSound;
AVAudioPlayer *audioPlayer;
- (id)init
{
self = [super initWithNibName:@"MediaPlayerViewController" bundle:nil];
if (self) {
NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"Music"
ofType:@"mp3"];
if (musicPath) {
NSURL *musicURL = [NSURL fileURLWithPath:musicPath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL
error:nil];
[audioPlayer setDelegate:self];
}
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound12"
ofType:@"aif"];
我们可以在一个button的点击事件中开始播放这个mp3文件,如:
- (IBAction)playAudioFile:(id)sender
{
if ([audioPlayer isPlaying]) {
// Stop playing audio and change text of button
[audioPlayer stop];
[sender setTitle:@"Play Audio File"
forState:UIControlStateNormal];
}
else {
// Start playing audio and change text of button so
// user can tap to stop playback
[audioPlayer play];
[sender setTitle:@"Stop Audio File"
forState:UIControlStateNormal];
}
}
这样运行我们的程序,就可以播放音乐了。
这个类对应的AVAudioPlayerDelegate有两个委托方法。一个是 audioPlayerDidFinishPlay
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
successfully:(BOOL)flag
{
[audioButton setTitle:@"Play Audio File"
forState:UIControlStateNormal];
}
另一个是audioPlayerEndInterrupti
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
[audioPlayer play];
}