Sunday, May 29, 2016

Play a sound file with AVAudioPlayer

The example below plays an audio file in Swift 2.2 with Xcode 7.3.1.

1. Drag and add the example.mp3 sound file to the project.

2. Modify ViewController.swift as:


import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var button : UIButton!
    var buttonStop : UIButton!
    
    var player : AVAudioPlayer!
    let url = NSBundle.mainBundle().URLForResource("example", withExtension: "mp3")!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Play/Pause button
        button = UIButton(frame: CGRectMake(0, 0, 200, 30))
        button.center = view.center
        button.setTitle("Play", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        button.addTarget(self, action: #selector(buttonPressed), forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
        
        //Stop button
        buttonStop = UIButton(frame: CGRectMake(0, 0, 200, 30))
        buttonStop.center = CGPointMake(view.center.x, view.center.y+100)
        buttonStop.setTitle("Stop", forState: UIControlState.Normal)
        buttonStop.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonStop.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        buttonStop.addTarget(self, action: #selector(buttonStopPressed), forControlEvents: UIControlEvents.TouchUpInside)
        buttonStop.hidden = true
        view.addSubview(buttonStop)
        
        do {
            player = try AVAudioPlayer(contentsOfURL: url)
        } catch {
            print("Error!")
        }
    }
    
    func buttonPressed() {
        if player.playing {
            player.pause()
            button.setTitle("Play", forState: UIControlState.Normal)
        } else {
            player.play()
            button.setTitle("Pause", forState: UIControlState.Normal)
            buttonStop.hidden = false
        }
    }
    
    func buttonStopPressed() {
        player.stop()
        player.currentTime = 0 //rewind
        buttonStop.hidden = true
        button.setTitle("Play", forState: UIControlState.Normal)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

No comments:

Post a Comment