我想制作它,以便可以单击一个按钮,它将反复启动一遍又一遍地播放系统声音(无需重叠声音)直到再次单击按钮 - 因此,从本质上讲,按钮将重复播放音频服务系统的声音。
如果有人知道该怎么做,我将非常感谢。
谢谢
进行此操作,使用无限重复的AVAudioplayer
,然后在按下按钮时暂停/播放它。首先制作一个函数的AudioPlayer变量, :
var audioPlayer : AVAudioPlayer!
然后在ViewDidload的内部初始化AudiOplayer:
override func viewDidLoad() {
super.viewDidLoad()
guard let url = Bundle.main.path(forResource: "myOwnSound", ofType: "wav") else { //your own file name AND extension type of course
print("file not found")
return
}
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOf: URL(string: url)!)
audioPlayer!.prepareToPlay()
audioPlayer.numberOfLoops = -1
} catch let error as NSError {
print("error while initialising sound: (error)")
}
}
然后在链接到您的按钮的函数中,在我的情况下,我命名了该功能按钮:
@IBAction func buttonPress(_ sender:AnyObject){
if audioPlayer.isPlaying {
audioPlayer.pause()
}
else {
audioPlayer.play()
}
}
您可以使用
AVFoundation
和AVAudioPlayer
来管理音乐和 您的应用程序内部的声音
以下导入
import AVFoundation
创建Avaudioplayer的属性来管理播放/停止并在音乐按钮范围内添加以下代码
var player : AVAudioPlayer?
@IBAction func openListAction(_ sender: UIButton) {
// moveToGame()
if sender.isSelected {
sender.isSelected = false
player?.stop()
}
else {
sender.isSelected = true
let bundle = Bundle.init(for: self.classForCoder)
let path = bundle.path(forResource: "soundFileName", ofType : "soundFileExtension")! //.mp3, .caf etc
let url = URL(fileURLWithPath : path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch {
print ("Error to load music")
}
}
}