Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing audio in asset library

I'm trying to load/play an audio file store in the assets library but for some reason it can not be found in the bundle.

enter image description here Here is my code:

func playAudio() {

    let path = Bundle.main.path(forResource: "sound", ofType:nil)!
    let url = URL(fileURLWithPath: path)

    do {
       sound = try AVAudioPlayer(contentsOf: url)
        sound?.play()
    } catch {
        // do something
    }
}

Any of you knows what I'm doing wrong? or why Xcode can not find the file?

like image 761
user2924482 Avatar asked Aug 04 '18 22:08

user2924482


People also ask

What is an audio asset?

A Sound Recording asset represents an audio recording, typically provided by a music label. The asset has metadata like ISRC, artist, and album, and a reference consisting of an audio master recording.

How do I upload an audio file to SharePoint?

Click From SharePoint.Browse to a location on your site, such as an Assets Library, where video and audio files are saved. Select the file that you want, and then click Insert.


2 Answers

but for some reason it can not be found in the bundle

Because it is not in the bundle. It is in the asset catalog.

Use the NSDataAsset class to fetch it.

let data = NSDataAsset(name: "sound")!
like image 198
matt Avatar answered Oct 14 '22 10:10

matt


How to play audio from asset catalog

  1. create a new "data set" asset in your asset catalog (NOT an image asset)

  2. drag the audio file on it and name it correctly e.g. "mySound" (avoid names that are already used for image assets)

  3. play it via playAudioAsset("mySound") using the code above

    Class MyClass {
    
       var audioPlayer: AVAudioPlayer!
    
       ...
    
       func playAudioAsset(_ assetName : String) {
          guard let audioData = NSDataAsset(name: assetName)?.data else {
             fatalError("Unable to find asset \(assetName)")
          }
    
          do {
             audioPlayer = try AVAudioPlayer(data: audioData)
             audioPlayer.play()
          } catch {
             fatalError(error.localizedDescription)
        }
    } 
    
like image 27
Jochen Holzer Avatar answered Oct 14 '22 10:10

Jochen Holzer