AVAudioPlayer working in Simulator, but not on device

流过昼夜 提交于 2019-12-03 22:55:58

Make sure your iPhone's "Ringer Button" isn't showing the color red.

Some code I know works:

- (void)playOnce:(NSString *)aSound {

// Gets the file system path to the sound to play.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];  

// Converts the sound's file path to an NSURL object
NSURL *soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = soundURL;
[soundURL release];

AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error:nil];  
self.theAudio = newAudio; // automatically retain audio and dealloc old file if new file is loaded

[newAudio release]; // release the audio safely

[theAudio prepareToPlay];

// set it up and play
[theAudio setNumberOfLoops:0];
[theAudio setVolume: volumeLevel];
[theAudio setDelegate: self];
[theAudio play];

}

Here's a quick, simple thing to try:

I ran into a similar issue with images as well as sounds. The iPhone is cap-sensitive, even the file extensions, but the simulator is not. Check the NSURL object != nil in addition to soundObject.

You may also want to try [[NSBundle mainBundle] URLForResource:@"sound" ofType:@"mp3"]; and make sure the file is being copied into the .app under YourApp.app/Resources/

-Stephen

when something works on simulator and not on the device, the first thing to do is to restart the device and check. sometimes restarting the device has worked for me and saved a lot of time. Otherwise then you can start debugging

I had sound in simulator, but not on device. It started working when I set AVAudioPlayer delegate

If you are running code on iOS 10 simulator it does not ask for security permissions but, If you are running code on ios 10 device then you need to add audio permission key in plist. Add Privacy - Microphone Usage Description key in plist.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!