无法在xcode 6 swift中播放音频

时间:2014-11-30 11:05:03

标签: xcode audio swift

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()
    }

1 个答案:

答案 0 :(得分:0)

我通常会制作一个声音类,然后使用一个函数来调用声音,就像这样:

声音等级:

class Sound {
    //properties
    var fileName = ""
    var fileExtension = ""

    //custom init
    init(fileName: String, fileExtension: String) {
        self.fileName = fileName
        self.fileExtension = fileExtension
    }
}

playSound功能:

  

//需要AVAudioPlayer吗?实例

     

//需要AVFoundation导入

     

//需要AVAudioPlayerDelegate

     

var audioPlayer:AVAudioPlayer()

     

func playSound(声音:声音){

     

让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 */
        }
    }

})

希望这可以帮到你。