您的位置:首页 > 移动开发 > IOS开发

【iOS】音频的简单使用(1播放音乐)

2016-08-24 00:00 621 查看
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
/*单个声音,需要全局*/
- (void)playSound:(NSString*)name
{
/************ 增加启动声音 **************/
//1.音频文件的url路径
NSURL *url=[[NSBundle mainBundle] URLForResource:name withExtension:Nil];
//2.创建播放器(注意:一个AVAudioPlayer只能播放一个url)
_audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
//3.缓冲
[_audioPlayer prepareToPlay];
//4.播放
[_audioPlayer play];
}

/*other.uiviewcontroller*/
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@property (strong, nonatomic) AVAudioPlayer *beginPlayer;
@property (strong, nonatomic) AVAudioPlayer *pullPlayer;

/*多个声音*/
- (void)initSound
{
/************ 增加声音 *********声音文件放在bundley文件下*****/
NSString *bundlePath =[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"sound.bundle"];
NSURL *urlb = [NSURL fileURLWithPath:[bundlePath stringByAppendingPathComponent:@"ja.wav"]];
NSURL *urlp = [NSURL fileURLWithPath:[bundlePath stringByAppendingPathComponent:@"jb.wav"]];
NSURL *url = [NSURL fileURLWithPath:[bundlePath stringByAppendingPathComponent:@"jc.wav"]];

_beginPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:urlb error:Nil];
[_beginPlayer prepareToPlay];

_pullPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:urlp error:Nil];
[_pullPlayer prepareToPlay];

_audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];
[_audioPlayer prepareToPlay];
/*声音停止通知*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(soundStop) name:Notification_sound_Key object:nil];

}

- (void)plays
{
[_audioPlayer play];
}

- (void)soundStop
{
[_beginPlayer stop];
[_pullPlayer stop];
[_audioPlayer stop];
}

以上代码适合,播放mp3这种格式的长音频文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS AVAudioPlayer