简体   繁体   中英

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

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
  • In Swift 3 a lot of things was renamed and some of the "old" methods that took an &error parameter was changed to use do try catch instead. Therefore the error has gone from your call and has been replaced with a try .
  • The above will fail! You will see error code -10870 which can be found in the AUComponent.h header file and which translates to:

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)

So...this leads me to thinking you need to do one of two things, either:

  1. find a .midi file and use that with the AVMidiPlayer
  2. find something else to play your file, for instance AVFilePlayer or AVAudioEngine

(you can read more about error handling in Swift here ).

Hope that helps you.

The mp3 file must be in the Resources folder.

You play an mp3 with code like this (not the MIDI player):

if let url = Bundle.main.url(forResource: "drum01", withExtension: "mp3") {
  let player = try? AVAudioPlayer(contentsOf: url)
  player?.prepareToPlay()
  player?.play()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM