import UIKit
import AVFoundation
class PlaySoundViewController: UIViewController {
var audioplayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3") {
var fileUrl = NSURL.fileURLWithPath(filePath)
audioplayer = AVAudioPlayer(contentsOfURL: fileUrl, error: nil)
}else{
println("path file is empty")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func PlaySoundSlow(sender: UIButton) {
audioplayer.play()
}
I generally make a sound class, then use a function to call the sound into play, like this:
Sound Class:
class Sound {
//properties
var fileName = ""
var fileExtension = ""
//custom init
init(fileName: String, fileExtension: String) {
self.fileName = fileName
self.fileExtension = fileExtension
}
}
playSound Function:
// requires AVAudioPlayer? instance
// requires AVFoundation import
// requires AVAudioPlayerDelegate
var audioPlayer: AVAudioPlayer()
func playSound (sound: Sound) {
let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatchQueue, {[weak self] in let mainBundle = NSBundle.mainBundle() /* Find the location of our file to feed to the audio player */ let filePath = mainBundle.pathForResource(sound.fileName, ofType:sound.fileExtension) if let path = filePath{ let fileData = NSData(contentsOfFile: path) var error:NSError? /* Start the audio player */ self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error) /* Did we get an instance of AVAudioPlayer? */ if let player = self!.audioPlayer{ /* Set the delegate and start playing */ player.delegate = self if player.prepareToPlay() && player.play(){ /* Successfully started playing */ } else { /* Failed to play */ } } else { /* Failed to instantiate AVAudioPlayer */ } } })
Hopefully this helps you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.