我的摩尔斯电码转换器不会输出应有的声音。我已经测试了没有这个功能的扬声器和我的方法,并且它完美无缺,但它不与程序的其余部分相关。编译器没有给我任何错误,操场不会崩溃,它只是不播放声音。音量和铃声已满。
func speakTheCode(message: String) {
var speaker = AVAudioPlayer()
let longBeep = #fileLiteral(resourceName: "beep_long.mp3")
let shortBeep = #fileLiteral(resourceName: "beep_short.mp3")
let dash = "-"
let dot = "."
for character in message.characters {
if character == dash[dash.startIndex] {
speaker = try! AVAudioPlayer(contentsOf: longBeep)
speaker.prepareToPlay()
print("-")
}
else if character == dot[dot.startIndex] {
speaker = try! AVAudioPlayer(contentsOf: shortBeep)
speaker.prepareToPlay()
print(".")
}
speaker.play()
}
}
我几个小时以来一直在乱用代码而且没有任何工作。我做错了什么(如果有的话)?
答案 0 :(得分:0)
播放音频似乎存在一些游乐场问题。见这个主题:
Playing a sound in a Swift Playground
但是,我能够对您的代码进行一些更改并使其正常工作。这是我的代码:
Run
我必须启用无限期执行才能让代码执行完毕。此外,我在第二个音频文件加载时遇到了一些问题,但我没有进一步调查,看看它是否是我的测试文件或其他问题,因为它主要起作用。
答案 1 :(得分:-1)
@Fahim仍显示错误
类莫尔斯:NSObject,AVAudioPlayerDelegate { private var message =“” private var dotSound:AVAudioPlayer! private var dashSound:AVAudioPlayer! private let dash = Character(“ - ”) private let dot = Character(“。”) private var index:String.Index!
init(message:String) {
super.init()
do {
if let url = Bundle.main.url(forResource:"beep_short", withExtension:"mp3") {
self.dotSound = try AVAudioPlayer(contentsOf:url)
self.dotSound.delegate = self
self.dotSound.prepareToPlay()
}
} catch {
NSLog("Error loading dot audio!")
}
do {
if let url = Bundle.main.url(forResource:"beep_long", withExtension:"mp3") {
self.dashSound = try AVAudioPlayer(contentsOf:url)
self.dashSound.delegate = self
self.dashSound.prepareToPlay()
}
} catch {
NSLog("Error loading dash audio!")
}
self.message = message
self.index = message.startIndex
}
func playCharacter() {
let character = message.characters[index]
NSLog("Character: \(character)")
if character == dash {
dashSound.play()
} else if character == dot {
dotSound.play()
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
NSLog("Finished playing")
if index != message.endIndex {
self.index = message.index(after:index)
playCharacter()
}
}
}
让m =莫尔斯(消息:“...... - - ”) m.playCharacter()
PlaygroundPage.current.needsIndefiniteExecution = true