此範例為點擊按鈕觸發點擊按扭播放音樂,

順帶一提此程式需要在實機上執行才有效過, 模擬器則無法測試

Step1. 創建一個新專案, 加入一顆按鈕, 點擊可產生播放音樂, 將音樂檔案加入專案, 並建立Button與程式之關聯性

Step2. 加入AVFoundation.framework, 並#import <AVFoundation/AVFoundation.h>

Step3. 加入一個iVar, 資料型態為AVAudioPlayer, 並建立一物件命名*myPlayer

Step4. 加入以下程式碼在viewdidload已及button方法內 

ViewController.m 

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
{
    AVAudioPlayer *myPlayer;
}

@property (weak, nonatomic) IBOutlet UIButton *playBtn;
- (IBAction)clickBtn:(id)sender;
@end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *filePath =[[NSBundle mainBundle] pathForResource:@"demo" ofType:@"mp3"]; //加入音樂檔以及副檔名 if(filePath != nil) { NSURL *fileURL =[[NSURL alloc]initFileURLWithPath:filePath]; //指定檔案所在位址 myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil]; //將路徑餵給myPlayer myPlayer.numberOfLoops= -1; //預設音樂播放幾次, 無限循環為-1 myPlayer.volume=1.0; //預設音量, 1.0為最大音量 [myPlayer prepareToPlay]; [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlayback error:nil]; //設定播放形式 } } - (IBAction)clickBtn:(id)sender { [myPlayer play]; //呼叫播放方法 } @end
arrow
arrow
    文章標籤
    iOS objectiveC AVAudio
    全站熱搜

    Will 發表在 痞客邦 留言(0) 人氣()