问题描述
我有一个非常简单的单一视图中的代码Swift应用程序在我的 ViewController
:
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")
}
我已添加 import AVFoundation
和 audioPlayer
是一个全局变量。当我执行代码,它打印工作,所以它使通过没有错误,但没有声音播放。
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.
推荐答案
你的代码有很多错误,Socratic方法崩溃了,它可能是最简单的只是抛出它并显示你:
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.
一个最后一点,它可能或可能不相关:不是每个 m4a
文件可以播放。例如,高度压缩的文件可能会失败(双关语)。
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).
这篇关于AVAudioPlayer不在Swift播放音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!