简体   繁体   中英

Play sound when silent

I have a project where it is required to play a sound when the phone is in silent mode. This was possible in earlier versions of iOS, but it is not in iOS 8 or later using standard APIs.

I am now looking for a possibility to do this using a private API, I have looked thru the header files but I have not found the right one. I would guess an API like this exists but I don't know which. Any suggestions are appreciated.

Please note that solutions that make the play and pause button show is not acceptable. Please also note that I am looking for a private API and I am aware of all issues related to the fact that I am using private APIs. Furthermore playing a sound when the user has set the silent switch to on can make users angry in some cases, but in this case they will be angry if there is no sound (think alarm clock).

EDIT: Will need to do this from background, for example when receiving a push notification.

You did not specify language so I will just use Swift. The code is not really protected well but basically you need to set the AVAudioSession singleton's category to AVAudioSessionCategoryPlayback :

try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

// Then just play the file
guard let soundPath = NSBundle.mainBundle().pathForResource("sound", ofType: "wav") else {
    // bad path
    return
}

var soundFile = NSURL.fileURLWithPath(soundPath)

// Instance variable
player = try AVAudioPlayer(contentsOfURL: soundFile)
player.play()

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