Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

swift - Play local audio file with AVAudioPlayer

I'm testing my app in simulator.

I'm downloading file and getting it's local way like this one: file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3

Now I want to play this file with AVAudioPlayer but I'm always getting this error:

file:///
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"

Code for playing:

var alertSound = NSURL(fileURLWithPath: "file:///Users/administrator/Library/Developer/CoreSimulator/Devices/4CDF286B-543F-4137-B5E2-C312E19B992F/data/Containers/Data/Application/E5F13797-A6A8-48A1-B3C3-FBC3D7A03151/Documents/4d13e04980d3.mp3")
        print(alertSound)

        var error:NSError?
        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } catch {
            print(error)
        }

How should I make it playing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Under iOS8, the path that you have saved won't be valid across launches. The id you see "E5F13797-A6A8-48A1-B3C3-FBC3D7A03151" will change with each launch.

The solution is to save the filename and not the complete path, and to recreate the URL or complete path, by getting the path to the Documents (or tmp) folder and appending the filename to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...