【Swift】Web上から音声ファイルをダウンロードして再生する

前回の投稿で作成したAVAudioPlayerUtil.swiftを流用し、urlから音声ファイルを直接ダウンロードして再生するだけの機能を作りました。

環境

  • OSX Yosemite v10.10.5
  • Xcode v7.0 beta6
  • 検証端末 iPhone6 v8.4.1

AVAudioPlayerUtil.swift

前回の投稿を参照してください。

ViewController.swift

ViewControllerにNSURLSessionDownloadDelegateを継承させています。

import UIKit;

class ViewController: UIViewController,NSURLSessionDownloadDelegate {

    override func viewDidLoad() {
        super.viewDidLoad();
        // Do any additional setup after loading the view, typically from a nib.
        
        // 通信のコンフィグを用意
        let myConfig:NSURLSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("backgroundSession");
        
        // Sessionを作成する
        let mySession:NSURLSession = NSURLSession(
            configuration: myConfig,
            delegate: self,
            delegateQueue: nil);
        
        // ダウンロード先のURLからリクエストを生成
        let myURL:NSURL = NSURL(string: "http://hoge/fuga/***.mp3")!;
        let myRequest:NSURLRequest = NSURLRequest(URL: myURL);
        
        // ダウンロードタスクを生成
        let myTask:NSURLSessionDownloadTask = mySession.downloadTaskWithRequest(myRequest);
        
        // タスクを実行
        myTask.resume();
    }
    
    /*
    ダウンロード終了時に呼び出されるデリゲート
    */
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        
        AVAudioPlayerUtil.setValue(location);
        AVAudioPlayerUtil.play();
    }
    
    /*
    タスク終了時に呼び出されるデリゲート
    */
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning();
        // Dispose of any resources that can be recreated.
    }
}