Saturday, April 11, 2015

How to add audio to a Swift based iOS app


Setting up the app
  • Create a new Single Page Application 
  • Open the ViewController.swift file
  • Add the AVFoundation module to your import statements
Initiate the player 
  • var audioPlayer:AVAudioPlayer!
Get a handle on the file path 
  • if var filePath = NSBundle.mainBundle().pathForResource("file_name", ofType: "mp3"){ }
Convert filepath String data type to NSURL data type 
  • var filePathUrl = NSURL.fileURLWithPath(filePath)
  • Implement playback controls 
    • audioPlayer.stop()
    • audioPlayer.rate = 0.5
    • audioPlayer.currentTime = 0.0
    • audioPlayer.play()

    The following code is a concrete working example of the AVFoundation module that I implement as part of Udacity's iOS Nanodegree program.
     //  
     // PlaySoundsViewController.swift
     // Pitch Perfect 
     //  
     // Created by Michael Droz on 4/11/15.  
     // Copyright (c) 2014 Benefakter Apps by Michael Droz. All rights reserved.  
     // 
    
    import UIKit
    import AVFoundation
    
    class PlaySoundsViewController: UIViewController {
        
        var audioPlayer:AVAudioPlayer!
        
        @IBOutlet weak var stopButton: UIButton!
        
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            stopButton.enabled = false
            //get handle on audio file
            if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3"){
                var filePathUrl = NSURL.fileURLWithPath(filePath)
                audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
                audioPlayer.enableRate = true
                
            }else {
                println("error retrieving file path")
            }
                }
        
        @IBAction func playSlowAudio(sender: UIButton) {
            audioPlayer.stop()
            audioPlayer.rate = 0.5
            audioPlayer.currentTime = 0.0
            audioPlayer.play()
            stopButton.enabled = true
            
        }
        
        @IBAction func playFastAudio(sender: UIButton) {
            audioPlayer.stop()
            audioPlayer.rate = 1.5
            audioPlayer.currentTime = 0.0
            audioPlayer.play()
            stopButton.enabled = true
        }
        
        @IBAction func stopPlayingAudio(sender: UIButton) {
            
            audioPlayer.stop()
            stopButton.enabled = false
        }
        
        
            }
    
    

    No comments:

    Post a Comment