您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 學習筆記(三):音訊與影片播放

編輯:iOS 開發綜合

1、聲音播放

NSString *path = [[NSBundle mainBundle] pathForResource:@"win" ofType:@"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound(soundID);

2、音訊播放+震動

使用 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 釋放資源。

3、MP3 播放

背景音樂播放支援 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];
}

4、影片播放

使用 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;
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved