AVAudioPlayer working on Simulator but not on Real Device
On a real device, it needs to setCategory()
for AVAudioSession.sharedInstance()
And a fixed project can be downloaded here too.
func setupRecorder(){
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch let error as NSError {
print(error.description)
}
let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
AVNumberOfChannelsKey : NSNumber(int: 1),
AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Max.rawValue))]
do{
try soundRecorder = AVAudioRecorder(URL: getFileURL(), settings: recordSettings)
soundRecorder.delegate = self
soundRecorder.prepareToRecord()
}
catch let error as NSError {
error.description
}
}
NOTE: An audio session is the intermediary between your app and iOS used to configure your app’s audio behaviour. If we set category for AVAudioSessionCategoryPlayAndRecord
, we define iOS audio behaviour to allow audio input (recording) and output (playback).
Referred from: Audio Session Programming Guide
Audio is playing in simulator but not on device
Try to configure AVAudioSession shared instance prior to recording.
Like this:
// Configure AVAudioSession
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {
assertionFailure("Failed to configure `AVAAudioSession`: \(error.localizedDescription)")
}
sound is playing in simulator but not on physical device
Double check the code you've posted is not falling into the catch block. You should see an error in the console if an error is produced.
do {
print("ran")
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch let error {
print(error.localizedDescription)
}
You should also check the device is not on silent. To prevent this you can use the below that will always the play the audio as the audio sessions category will be set to .playback
do {
try AVAudioSession.sharedInstance().setCategory(.playback)
} catch let error {
print(error.localizedDescription)
}
Audio player works in simulator but not on iOS device
The proper way to get the path of a file in your app bundle is like this:
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];
But if you actually want an NSURL
, use the following to get it directly:
NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"mp3"];
Also, the simulator isn't case sensitive but a real device is. Make sure your file is really named test.mp3
and not something like Test.mp3
. Update the name in the code to match the actual filename.
Use the debugger to make sure that soundURL
isn't nil
. If not but the audio player still doesn't work, use the error
parameter to see why:
NSError *error = nil;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&error];
if (!_audioPlayer) {
NSLog(@"Unable to create audio player: %@", error);
}
AVAudioPlayer not playing on some devices
I have found the solution.
On problematic devices, "mute" was on, affecting some of the sounds in the device. To prevent this, call this somewhere on beginning of your app:
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
This will cause the audio to be treated as playback and thus not be muted by the mute option.
I have learned that users typically don't know where to find the mute on/off control. On iPad Air 2: raise the lower pane from bottom and press the speaker icon.
SwiftUI background mode works in simulator but not on a real device?
Add the following ode just at the beginning of OnAppear
,
Your code would look like this:
.onAppear {
// 1
let session = AVAudioSession.sharedInstance()
do{
// 2
try session.setActive(true)
// 3
try session.setCategory(.playback, mode: .default, options: .defaultToSpeaker)
} catch{
// 4
print(error.localizedDescription)
}
let originalUrl = "https://some-UR-to-the-Audio-file"
let urlString = originalUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
player = AVPlayer(url: URL(string: urlString!)!)
player.play()
}
- Returns the shared audio session instance.
- Activates your app’s audio session.
- Sets the audio session’s category, mode, and options. The audio session’s
category
andmode
together define how your app uses audio. - Catch and print any error that may occur.
Related Topics
Coretelephony Esim Functions Not Working on Device
How to Set the Local Storage Before a Uiwebview Loading Its Initial Request
How to Cluster Custom Icons Markers in Googlemaps for iOS
iOS Do Scheduled Operation in Background or When App Active
Circular Button Becomes Rounded Rectangle After Size Increase
iOS 8: Autorotation Is Not Working Without Storyboard
No Such Module "Sinch" Xcode 9.1 Swift 4
How to Transfer Data Between Parent and Child View Controllers
Swift/How to Call Delegate with Popviewcontroller
Get Light or Dark Variant of a Color Declared in Assets
Facebook Sdk Login Throws Error in Swift 2 iOS 9
Passing Data Between Views in One Viewcontroller in Swift
Skaction Works in Didmovetoview But Doesn't Works in Function
Swift Swipe Navigation Table Views
Swift Save Viewcontroller State Using Coder Beyond App Close