NSString *path = [[NSBundle mainBundle] pathForResource:@"win" ofType:@"wav"]; SystemSoundID soundID; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID); AudioServicesPlaySystemSound(soundID);
使用 AudioToolbox 框架,可播放系統音效、提示音與觸發震動。限制包括:聲音長度需小於 30 秒、格式為 linear PCM 或 IMA4、檔案需為 .caf/.aif/.wav,且無法控制播放進度、不支援循環與立體聲。
// 建立音效物件
-(void) GetPlaysound {
[self stopplaysound];
NSInteger row = [soundPicker selectedRowInComponent:0];
NSString *soundfilename;
switch (row) {
case 0: soundfilename = @"sound1.aiff"; break;
case 1: soundfilename = @"sound2.aiff"; break;
case 2: soundfilename = @"sound3.aiff"; break;
default: break;
}
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSURL *soundfileURL = [NSURL fileURLWithPath:[Path stringByAppendingPathComponent:soundfilename]];
AudioServicesCreateSystemSoundID((CFURLRef)soundfileURL, &soundFileObject);
if ([swcallback isOn]) {
AudioServicesAddSystemSoundCompletion(soundFileObject, NULL, NULL, completionCallback, (void*)self);
}
}
- (IBAction) playSystemSound {
[self GetPlaysound];
AudioServicesPlaySystemSound(self.soundFileObject);
}
- (IBAction) vibrate {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); // 震動
}
需引入 AudioToolbox.framework,並在 dealloc 中呼叫 AudioServicesDisposeSystemSoundID 釋放資源。
背景音樂播放支援 mp3、可循環播放長音樂,需引入 AVFoundation:
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;
[myBackMusic prepareToPlay];
[myBackMusic setVolume:1];
myBackMusic.numberOfLoops = -1; // -1 為一直循環
if (mainMusicStatus) {
[myBackMusic play];
}
使用 MediaPlayer 框架的 MPMoviePlayerController:
#import <MediaPlayer/MediaPlayer.h>
-(IBAction)ok {
NSURL *url = [self localMovieURL];
[self initAndPlayMovie:url];
}
-(void)initAndPlayMovie:(NSURL *)movUrl {
MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] initWithContentURL:movUrl];
if (mp) {
self.moviePlayer = mp;
[mp release];
[self.moviePlayer play];
self.moviePlayer.view.frame = CGRectMake(0, 0, 320, 300);
[self.view addSubview:moviePlayer.view];
}
}
-(NSURL *)localMovieURL {
if (movieURL == nil) {
NSBundle *bundle = [NSBundle mainBundle];
if (bundle) {
NSString *moviePath = [bundle pathForResource:@"Movie" ofType:@"m4v"];
if (moviePath) {
self.movieURL = [NSURL fileURLWithPath:moviePath];
}
}
}
return self.movieURL;
}