简体   繁体   中英

Swift/iOS: AVAudioPlayer does not play sound in NSData format

I am trying to create an AVAudioPlayer that plays NSData downloaded from Parse.

I am pretty certain the sound ( .wav format) has been uploaded to Parse. I am also certain that the sound can be downloaded from Parse in the NSData format. So I am creating an AVAudioPlayer object using the downloaded data from Parse:

if audioData != nil {
                    print("successful downloading audio!") //this prints out
                    let audioPlayer = try! AVAudioPlayer(data: audioData!, fileTypeHint: AVFileTypeWAVE)
                    audioPlayer.prepareToPlay()
                    audioPlayer.volume = 0.5
                    audioPlayer.play()
                }

As you can see above, the audioPlayer is created, but it does not play the sound. Where might be wrong?

Is this code within a function? If so, your making the audioPlayer variable locally. This means that the audioPlayer is created, starts playing and then is deallocated (at the end of the function call), resulting in no audio. Your audioPlayer object needs to be a class property or within global space (such as a singleton for example), so the object life persists after the function ends.

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