1、背景音樂播放 支持mp3格式 循環播放長音樂
這種播放音樂的方式導入框架#import <AVFoundation/AVFoundation.h>;
NSString *musicFilePath = [[NSBundle mainBundle] pathForResource"changan" ofType"mp3"]; //創建音樂文件路徑
NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
AVAudioPlayer *thePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
// 創建播放器
self.myBackMusic = thePlayer; //賦值給自己定義的類變量
[musicURL release];
[thePlayer release];
[myBackMusic prepareToPlay];
[myBackMusic setVolume:1]; //設置音量大小
myBackMusic.numberOfLoops = -1;//設置音樂播放次數 -1為一直循環
if (mainMusicStatus)
{
[myBackMusic play]; //播放
}
--------------------------------------------------------------------------------
2、按鈕播放聲音
需要導入框架#import <AudioToolbox/AudioToolbox.h>
NSString *thesoundFilePath = [[NSBundle mainBundle] pathForResource"Clapping Crowd Studio 01" ofType"caf"]; //創建音樂文件路徑
CFURLRef thesoundURL = (CFURLRef) [NSURL fileURLWithPath:thesoundFilePath];
AudioServicesCreateSystemSoundID(thesoundURL, &sameViewSoundID);
//變量SoundID與URL對應
AudioServicesPlaySystemSound(sameViewSoundID); // 播放SoundID聲音 |