Gurpreet Paul
Gurpreet Paul

Reputation: 17

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!)
    }

Hello Audio The operation couldn't be completed

Upvotes: 0

Views: 339

Answers (2)

Lou Franco
Lou Franco

Reputation: 89222

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()
}

Upvotes: 0

pbodsk
pbodsk

Reputation: 6876

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:

  • printinstead 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.

Upvotes: 1

Related Questions