您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 播放本機音樂與線上影片的兩種寫法

編輯:iOS 相關資訊

音樂播放

播放 App 內建的音频檔案,用 AVAudioPlayer 最合適:

NSString *path = [[NSBundle mainBundle] pathForResource:@"預謀" ofType:@"mp3"];

if (path) {
    NSURL *url = [NSURL fileURLWithPath:path];
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    player.delegate = self;
    player.volume = 1;
    player.pan = 1;
    player.numberOfLoops = -1;   // -1 代表無限循環

    if ([player prepareToPlay]) {
        NSLog(@"prepareToPlay: %@", path);
        [player play];
    } else {
        NSLog(@"no prepareToPlay");
    }
}

這裡最關鍵、也最容易翻車的一點是 player 的參考週期。如果你在函式內部用區域變數持有 player,那麼函式執行完、區域變數離開作用域之後,這個播放器就會被釋放,聲音戛然而止。請務必用一個有較長生命週期的屬性(例如 view controller 的成員屬性)來持有它。網路上有些範例會在函式結尾加上 sleep 讓它「不要那麼快消失」,但那會直接堵死主執行緒,絕對不該用在正式程式碼裡。

另外提醒,AVAudioPlayer 使用前要記得引入 AVFoundation,並在需要背景播放或靜音鍵行為特殊處理時,透過 AVAudioSession 設定合適的 category。

影片播放

播放線上串流(含 m3u8)則可以用 MPMoviePlayerViewController:

NSURL *movieURL = [NSURL URLWithString:@"https://v.youku.com/player/getRealM3U8/vid/XNDUwNjc4MzA4/type/video.m3u8"];
MPMoviePlayerViewController *player =
    [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
[self presentMoviePlayerViewControllerAnimated:player];

這個做法的好處是系統自帶完整播放控制介面,幾行就能跑起來。需要注意的是,MPMoviePlayerViewController 在 iOS 9 已被標記為廢棄,新專案請改用 AVPlayerViewController;兩者的 presentation 方式類似,但 AVPlayerViewController 需要你把 AVPlayer 綁到它的 player 屬性上。另外,如果影片來源是 http,在啟用 ATS 的環境下會被系統攔截,記得改用 https 或相應調整設定。

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