gpt4 book ai didi

swift - 使用 AKAudioPlayer 播放声音 - iOS

转载 作者:可可西里 更新时间:2023-11-01 01:34:46 25 4
gpt4 key购买 nike

如何声明AKAudioPlayer

我正在使用 AudioKit Lib,我只需要帮助来播放带有更改文件按钮的 .wav 文件。

    import UIKit
import AudioKit

class ViewController: UIViewController {

let file = NSBundle.mainBundle().pathForResource("song", ofType: "wav")
let song = AKAudioPlayer(file!) // <--- ERROR = instance member 'file' cannot be used on type

override func viewDidLoad() {
super.viewDidLoad()

AudioKit.output = song
AudioKit.start()

song.play()
}


@IBAction func btn(sender: AnyObject) {

song.replaceFile("NewFile")
song.play()

}

}

最佳答案

这是解决您的问题的一种非常快速的方法。它可以做得更好,但至少你可以理解。

首先尝试创建一个新类,其中包含一个函数来播放您的文件,然后另一个函数来重新加载您的新替换文件,就像这样。

class PlayMyMusic {
var songFile = NSBundle.mainBundle()
var player: AKAudioPlayer!

func play(file: String, type: String) -> AKAudioPlayer {
let song = songFile.pathForResource(file, ofType: type)
player = AKAudioPlayer(song!)
return player
}

func rePlay(file: String, type: String, curPlay: AKAudioPlayer) {
let song = songFile.pathForResource(file, ofType: type)
curPlay.stop()
curPlay.replaceFile(song!)
curPlay.play()
}
}

在你的 View 中启动类

class testViewController: UIViewController {

let doPlay = PlayMyMusic().play("A", type: "wav")
.........
.........

在你的视野中播放你的音乐

override func viewDidLoad() {
super.viewDidLoad()

AudioKit.output = self.doPlay
AudioKit.start()
doPlay.looping = true
doPlay.play()

}

然后当你想重新加载一个新文件时使用重播功能

@IBAction func btn(sender: AnyObject) {
PlayMyMusic().rePlay("C", type: "wav", curPlay: self.doPlay)

}

关于swift - 使用 AKAudioPlayer 播放声音 - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38629766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com