AVAudioPlayer not playing audio in Swift

后端 未结 10 1437
抹茶落季
抹茶落季 2020-12-16 03:10

I have this code in a very simple, single view Swift application in my ViewController:

var audioPlayer = AVAudioPlayer()

@IBAction func playMyF         


        
10条回答
  •  温柔的废话
    2020-12-16 03:35

    There's so much wrong with your code that Socratic method breaks down; it will probably be easiest just to throw it out and show you:

    var player : AVAudioPlayer! = nil // will be Optional, must supply initializer
    
    @IBAction func playMyFile(sender: AnyObject?) {
        let path = NSBundle.mainBundle().pathForResource("audioFile", ofType:"m4a")
        let fileURL = NSURL(fileURLWithPath: path)
        player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
        player.prepareToPlay()
        player.delegate = self
        player.play()
    }
    

    I have not bothered to do any error checking, but the upside is you'll crash if there's a problem.

    One final point, which may or may not be relevant: not every m4a file is playable. A highly compressed file, for example, can fail silently (pun intended).

提交回复
热议问题