play audio from internet using AVAudioPlayer
I tried other method initWithData on AVAudioPlayer instead of initWithContentsOfURL. First try to get MP3 file into NSData and then play this data.
Look at my code here.
Playing a sound with AVAudioPlayer
Made modification to your code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav"))
println(alertSound)
// Removed deprecated use of AVAudioSessionDelegate protocol
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
Swift 3 and Swift 4.1:
import UIKit
import AVFoundation
class ViewController: UIViewController {
private var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "button-09", ofType: "wav")!)
print(alertSound)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try! audioPlayer = AVAudioPlayer(contentsOf: alertSound)
audioPlayer!.prepareToPlay()
audioPlayer!.play()
}
}
How to play audio using AVAudioPlayer in SwiftUI project
Is the audiofile there? Please select the project, go to Build Phases tab and under 'Copy Bundle Resources' you must see the audio file. If it is there then the problem is this.
I tried your code, it played the sound and then crashed. i changed it like this to make it work
@State var audioPlayer:AVAudioPlayer?
@State var isPlaying : Bool = false
var body: some View {
Button(action: {
if let path = Bundle.main.path(forResource: "a", ofType: ".mp3") {
self.audioPlayer = AVAudioPlayer()
self.isPlaying.toggle()
let url = URL(fileURLWithPath: path)
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: url)
self.audioPlayer?.prepareToPlay()
self.audioPlayer?.play()
}catch {
print("Error")
}
}
}, label: {
----
Have you considered separating your Audio model from your UI? It would make your code much clearer if you put it into separate Swift file
import AVFoundation
class Sounds {
static var audioPlayer:AVAudioPlayer?
static func playSounds(soundfile: String) {
if let path = Bundle.main.path(forResource: soundfile, ofType: nil){
do{
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer?.prepareToPlay()
audioPlayer?.play()
}catch {
print("Error")
}
}
}
}
And just one line to use it in UI
var body: some View {
Button(action: {
self.isPlaying.toggle()
Sounds.playSounds(soundfile: "0.wav")
}, label: {
I am trying to play audio from server using AVAudioPlayer, but file not Playing
Q: Does the AVAudioPlayer provide support for streaming audio content?
A: The AVAudioPlayer class does not provide support for streaming audio based on HTTP URL's. The URL used with initWithContentsOfURL: must be a File URL (file://). That is, a local path.
Source: https://developer.apple.com/library/ios/qa/qa1634/_index.html
Swift 3.0 AVAudioPlayer Playing audio over music
Set the audio session of your application to play over the currently playing audio:
try? AVAudioSession.sharedInstance().setActive(true)
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
According to the AVAudioSession
headers, AVAudioSessionCategoryAmbient
will play audio with music, etc.
/* Use this category for background sounds such as rain, car engine noise, etc.
Mixes with other music. */
public let AVAudioSessionCategoryAmbient: String
Related Topics
How to Convert Uicolor Value to a Named Color String
How to Use Both Google+ and Facebook Login in Same Appdelegate.Swift
How to Get Notified in Contact Changed Event in iOS
Swift: Navigate to New Viewcontroller Using Button
Toggling Airplane Mode in iOS Programmatically
Searching Nsarray of Nsdictionary Objects
Nsnumberformatter with Comma Decimal Separator
Uiimagejpegrepresentation Received Memory Warning
How to Get File Name in Uiimagepickercontroller with Asset Library
Uitableviewcell Auto Height Based on Amount of Uilabel Text
Best Way to Use Background Location Updates in iOS (Swift)
iOS 9 Objective-C Screen Size Issues
Inappropriate Expected Declaration Error
iPhone Uibutton - Image Position
Memory Leak When Using Nsurlsession.Downloadtaskwithurl