Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

ios - AVAudioPlayer not playing audio in Swift

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

var audioPlayer = AVAudioPlayer()

@IBAction func playMyFile(sender: AnyObject) {

    let fileString = NSBundle.mainBundle().pathForResource("audioFile", ofType: "m4a")
    let url = NSURL(fileURLWithPath: fileString)
    var error : NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
    audioPlayer.delegate = self
    audioPlayer.prepareToPlay()
    if (audioPlayer.isEqual(nil)) {
        println("There was an error: (er)")
    } else {
        audioPlayer.play()
        NSLog("working")
    }

I have added import AVFoundation and audioPlayer is a global variable. When I execute the code, it does print "working", so it makes it through without errors but no sound is played. The device is not in silent.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...