[英]how to add background music
The duplicate answer does not works at all 重复的答案并不在所有工作
import Cocoa
import AVFoundation
var error: NSError?
println("Hello, Audio!")
var url = NSURL(fileURLWithPath: "/Users/somebody/myfile.mid") // Change to a local midi file
var midi = AVMIDIPlayer(contentsOfURL: url, soundBankURL: nil, error: &error)
if midi == nil {
if let e = error {
println("AVMIDIPlayer failed: " + e.localizedDescription)
}
}
midi.play(nil)
while midi.playing {
// Spin (yeah, that's bad!)
}
I've made a couple of changes to your code but this seems to "work" (we'll get to that) 我对您的代码进行了几处更改,但这似乎“奏效”(我们将会解决)
First off, import the MP3 file to your playground as described in this answer 首先, 按照此答案中的说明将MP3文件导入到游乐场。
Then you can use your file like so: 然后,您可以像这样使用文件:
import UIKit
import AVFoundation
print("Hello, Audio!")
if let url = Bundle.main.url(forResource: "drum01", withExtension: "mp3") {
do {
let midi = try AVMIDIPlayer(contentsOf: url, soundBankURL: nil)
midi.play(nil)
while midi.isPlaying {
// Spin (yeah, that's bad!)
}
} catch (let error) {
print("AVMIDIPlayer failed: " + error.localizedDescription)
}
}
Notice: 注意:
print
instead of println
print
代替println
&error
parameter was changed to use do try catch
instead. &error
参数的“旧”方法被更改为使用do try catch
代替。 Therefore the error
has gone from your call and has been replaced with a try
. error
已从您的呼叫中消失,并已由try
代替。 AUComponent.h
header file and which translates to: AUComponent.h
头文件中找到,并转换为: kAudioUnitErr_UnknownFileType
kAudioUnitErr_UnknownFileType
If an audio unit uses external files as a data source, this error is returned
如果音频单元使用外部文件作为数据源,则返回此错误
if a file is invalid (Apple's DLS synth returns this error)
如果文件无效(Apple的DLS合成器返回此错误)
So...this leads me to thinking you need to do one of two things, either: 所以...这使我想到您需要执行以下两项操作之一:
AVMidiPlayer
AVMidiPlayer
AVFilePlayer
or AVAudioEngine
AVFilePlayer
或AVAudioEngine
(you can read more about error handling in Swift here ). (您可以在此处阅读有关Swift中错误处理的更多信息)。
Hope that helps you. 希望对您有帮助。
The mp3 file must be in the Resources folder. mp3文件必须位于Resources文件夹中。
You play an mp3 with code like this (not the MIDI player): 您使用以下代码播放mp3(而不是MIDI播放器):
if let url = Bundle.main.url(forResource: "drum01", withExtension: "mp3") {
let player = try? AVAudioPlayer(contentsOf: url)
player?.prepareToPlay()
player?.play()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.