我想在一个快速的操场上制作一个莫尔斯码转换器。我让转换工作,但我需要使代码与AVFoundation“说话”。如何解码莫尔斯代码字符串以播放每个'。'的短蜂鸣声。每个' - '的长哔声?
到目前为止,这是我的代码:
func speakTheCode(message: String) {
var speaker = AVAudioPlayer()
let longBeep = URL(fileURLWithPath: Bundle.main.path(forResource: "beep_long", ofType: "mp3")!)
let shortBeep = URL(fileURLWithPath: Bundle.main.path(forResource: "beep_short", ofType: "mp3")!)
try! speaker = AVAudioPlayer(contentsOf: longBeep)
try! speaker = AVAudioPlayer(contentsOf: shortBeep)
speaker.prepareToPlay()
}
答案 0 :(得分:1)
尝试将字符串解码为相应的音频。
func speakTheCode(message: String) {
var audioItems: [AVPlayerItem] = []
guard let longPath = Bundle.main.path(forResource: "beep_long", ofType: "mp3"),
let shortPath = Bundle.main.path(forResource: "beep_short", ofType: "mp3") else {
print("Path is not availabel")
return
}
let longBeep = AVPlayerItem(url: URL(fileURLWithPath: longPath))
let shortBeep = AVPlayerItem(url: URL(fileURLWithPath: shortPath))
for character in message.characters {
if character == Character("-") {
audioItems.append(longBeep)
} else if character == Character(".") {
audioItems.append(shortBeep)
}
}
let player = AVQueuePlayer(items: audioItems)
player.play()
}
speakTheCode(message: "..--..")