开发者

Choose custom sound for local notifications

How do you change the sound that plays for local notifications? I use the code below to play the default sound:

notif.soundName = UILocalNotificationDefaultSoundName;

So, I tried this below, and it didn't work. What should I do? Thanks for your help!

notif.sou开发者_JS百科ndName = @"sound.caf";


You can convert from wav and mp3 using:

afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf


That should work. Make sure the sound is actually in your app’s bundle, is in the correct format (linear PCM or IMA4—pretty much anywhere that explains how to convert sounds for iOS will tell you how to do that), and is under 30 seconds.


I also tried to convert mp3 to caf using command below:

afconvert clockalarm.mp3 clockalarm.caf -d ima4 -f caff -v

One lesson here: I spent several hours to struggle with the sound of local notification. Tried to convert with different bitrate and format. But finally I found that there must be a defect with the iOS 6.1 emulator. I deployed the code to device, it works well, but on emulator, does not have any sound.


I ran into all of these problems (thanks for the answers) and was able to solve the problem by converting from .wav to .caf (sans 6.1 simulator). The last bit I needed was to make sure the .caf was in the my app's bundle. To confirm/correct this...

Right click the file in the "Project Navigator", select "Show File Inspector" and make sure the file has a check mark next to your project in the "Target Membership" area. In my case "LocalNotificationExampleTests" was the only item checked. Checking "LocalNotificationExample" fixed my lack of sound on the device.


For Swift 3 use UNNotificationSound.init for the notif object in notification scheduling function.

Here's a Swift 3 example:

func scheduleNotifications(inSeconds: TimeInterval, completion: @escaping (_ Success: Bool) ->()){
        ...
        notif.sound = UNNotificationSound.init(named: "CustomSound.mp3") 
        ...
}

Final note, according to Apple: "The sound file must be contained in the app’s bundle or in the Library/Sounds folder of the app's data container. If files exist in both locations then the file in ~/Library/Sounds will be preferred."


Swift 5.1

How do you change the sound that plays for local notifications. I use the code below to play the default sound:

content.sound = UNNotificationSound.init(named: UNNotificationSoundName(rawValue: "Sound_Name.mp3"))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜