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

iOS 音訊播放:AVAudioPlayer 與 AVPlayer 入門

編輯:iOS 開發綜合

iOS 提供多種音訊播放方式,常見包含 AVAudioPlayer、AVPlayer 與 Audio Queue。若只是播放本地音檔,AVAudioPlayer 是最簡單直接的選擇。

三種常見播放方式

  • AVAudioPlayer:使用簡單,適合本地音檔,不支援網路串流。
  • AVPlayer:可播放本地與串流媒體,介面較精簡。
  • Audio Queue:API 較低階,適合需要細緻控制音訊資料的情境。

使用 AVAudioPlayer 播放音樂

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

@end
- (void)viewDidLoad {
    [super viewDidLoad];

    NSBundle *bundle = [NSBundle mainBundle];
    NSString *path = [bundle pathForResource:@"想你的夜" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];

    NSError *error = nil;
    self.audioPlayer =
        [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

    if (self.audioPlayer == nil) {
        NSLog(@"載入失敗: %@", error);
        return;
    }

    self.audioPlayer.volume = 0.8;
    self.audioPlayer.numberOfLoops = 0;
    self.audioPlayer.currentTime = 0;

    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
}

常用屬性

  • volume:音量,範圍約為 0.0 到 1.0。
  • numberOfLoops:播放次數,負數代表無限循環。
  • currentTime:目前播放位置,可指定起始點。
  • duration:音檔長度。

代理方法

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
                       successfully:(BOOL)flag {
    NSLog(@"播放結束");
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player
                                 error:(NSError *)error {
    NSLog(@"解碼錯誤: %@", error);
}

若播放過程可能被電話或系統提示打斷,也可透過 interruption 相關代理處理中斷與恢復。整體而言,AVAudioPlayer 很適合用於本地音效、背景音樂與簡單播放控制。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved