ios開發--音樂的播放
阿新 • • 發佈:2018-11-11
一、簡單說明
音樂播放用到的一個叫做AVAudioPlayer的類,這個類可以用於播放手機本地的音樂檔案 注意: (1)該類(AVAudioPlayer)只能用於播放本地音訊 (2)時間比較短的(稱之為音效)使用AudioServicesCreateSystemSoundID來建立,而本地時間較長的(稱之為音樂)使得AVAudioPlayer類。二、程式碼示例
AVAudioPlayer類依賴於AVFoundation框架,因此使用該類必須先匯入AVFoundation框架,幷包含其標頭檔案(包括主標頭檔案即可)。 匯入必要的,需要播放的音訊檔案到專案中。 程式碼示例:
程式碼說明 :執行程式,點選模擬器介面,卻並沒有能夠播放音訊檔案,原因是程式碼中建立的AVAudioPlayer的播放器是一個區域性變數,應該調整為全域性屬性。 可將程式碼調整如下,即可播放音訊#import "YYViewController.h" #import <AVFoundation/AVFoundation.h> @interface YYViewControllerr () @end @implementation YYViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //音訊檔案的url路徑 NSURL *url = [NSBundle mainBundle]URLForResource:@"23513.mp3" withExtension:Nil]; //建立播放器 AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil]; //緩衝 [audioPlayer prepareToPlay]; //播放 [audioPlayer play]; } @end