SharingMusicPlayer.swift:12:79:无法转换“AVAudioPlayer.Type”类型的值;预期参数类型“AVAudioPlayer”
这就是我在单例中的内容:
import AVFoundation
import Foundation
class SharingMusicPlayer {
static let sharingMusicPlayer = SharingMusicPlayer(backgroundMusicPlayer: AVAudioPlayer)
let backgroundMusicPlayer : AVAudioPlayer
private init(backgroundMusicPlayer: AVAudioPlayer) {
self.backgroundMusicPlayer = backgroundMusicPlayer
}
func playMusic() {
// open and play an mp3 file...
}
}
但我收到此错误:
SharingMusicPlayer.swift:12:79: Cannot convert value of type 'AVAudioPlayer.Type' to expected argument type 'AVAudioPlayer'
这是我调查过的另一篇文章,但该解决方案似乎不适用于此处:
“无法将“AVAudioPlayer.Type”类型的值转换为预期的参数类型”
顺便说一句,我的单例模式基于这篇文章:
https://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift
有人有什么建议吗?
更新:
请注意,我意识到我可以使用以下代码在我的应用程序中播放声音:
run(SKAction.playSoundFileNamed("MySound.mp3", waitForCompletion: false))
但我想在这种情况下播放背景音乐,因此上述方法不起作用。
This is what I have in my singleton:
import AVFoundation
import Foundation
class SharingMusicPlayer {
static let sharingMusicPlayer = SharingMusicPlayer(backgroundMusicPlayer: AVAudioPlayer)
let backgroundMusicPlayer : AVAudioPlayer
private init(backgroundMusicPlayer: AVAudioPlayer) {
self.backgroundMusicPlayer = backgroundMusicPlayer
}
func playMusic() {
// open and play an mp3 file...
}
}
But I am getting this error:
SharingMusicPlayer.swift:12:79: Cannot convert value of type 'AVAudioPlayer.Type' to expected argument type 'AVAudioPlayer'
Here is another post I have investigated but the solution does not appear to apply here:
"Cannot convert value of type 'AVAudioPlayer.Type' to expected argument type"
BTW, I based my singleton pattern on this article:
https://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift
Does anyone have any suggestions?
UPDATE:
Please note that I realize that I can play a sound in my app using this code:
run(SKAction.playSoundFileNamed("MySound.mp3", waitForCompletion: false))
But I want to play background music in this case so the above doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您需要传递
AVAudioPlayer
的实例
时,您将传递type
AVAudioPlayer。我想这应该有效:更改
为
Update
这是我最后编译的完整代码
You are passing it the
type
AVAudioPlayer when you need to pass aninstance
ofAVAudioPlayer
. This should work I guess:Change
to
Update
This is the full code that compiles at my end
这就是我想到的,尽管我仍然不确定这是否是快速执行单例的正确方法:
然后这就是我调用函数来启动和停止音乐的方法:
请注意,上面的按钮是在
SpriteKit
中,因此它们与Main.storyboard
中常见的UIButton
对象不同。This is what I came up with, though I am still not sure if this is the right way to do a singleton in swift:
Then this is how I would call the functions to start and stop the music:
Please note that the above buttons are in
SpriteKit
so they are different than the usualUIButton
objects inMain.storyboard
.