"AudioPlayerViewController.h"
@interface AudioPlayerViewController : UIViewController {
//產生AVAudioPlayer object
AVAudioPlayer *audioPlayer;
//產生UISwitch object
UISwitch *switched;
}
@property(nonatomic,retain)IBOutlet UISwitch *switched;
-(IBAction)switchange:(id)sender;
@end
"AudioPlayerViewController.m"
#import "AudioPlayerViewController.h"
@implementation AudioPlayerViewController
@synthesize switched;
-(IBAction)switchange:(id)sender
{
UISwitch *whichswitch=(UISwitch *)sender;
//當switch的按鈕切換到ON
if (whichswitch.isOn==YES) {
//讓audioPlayer可以重頭播放
audioPlayer.currentTime = 0;
//開始播放
[audioPlayer play];
}
else
//停止播放 但不會讓音樂重頭播放
[audioPlayer stop];
}
//程式剛起始時 會運作的部分
- (void)viewDidLoad {
[super viewDidLoad];
//指定音樂檔名和格式
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audio.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
}
- (void)dealloc {
//記得釋放記憶體
[audioPlayer release];
[super dealloc];
}
@end
最後記得 點xcode旁邊有個Resources 右鍵 add->existing files
選擇你想播放的音樂 記得將"copy items into destination group...."打勾 按add就可以了
另外還有一些其他method 像是
// 0.0 - no volume; 1.0 full volume
audioPlayer.volume = 0.5;
//暫停
[audioPlayer pause];
沒有留言:
張貼留言