Play a short sound in iOS

前端 未结 13 725
悲哀的现实
悲哀的现实 2020-11-27 10:23

I guess I could use AVAudioPlayer to play a sound, however, what I need is to just play a short sound and I don\'t need any loops or fine-grained control over t

相关标签:
13条回答
  • 2020-11-27 11:05

    Recently, I used this code to play short mp3 audio which worked fine:-

    Declare this below the @implementation

    NSString *path;
    
    NSURL *url;
    
    //where you are about to add sound 
    
    path =[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"quotes_%d",soundTags] ofType:@"mp3"];
    
        url = [NSURL fileURLWithPath:path];
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
        [player setVolume:1.0];
        [player play];
    
    //just add AVFoundation framework
    
    0 讨论(0)
  • 2020-11-27 11:05

    I used this code to play a short aiff-sound on iOS

    #import <AudioToolbox/AudioServices.h> 
    
    SystemSoundID completeSound;
    NSURL *audioPath = [[NSBundle mainBundle] URLForResource:@"downloadCompleted" withExtension:@"aiff"];
    AudioServicesCreateSystemSoundID((CFURLRef)audioPath, &completeSound);
    AudioServicesPlaySystemSound (completeSound);
    

    Hope this helps.

    0 讨论(0)
  • 2020-11-27 11:08

    SIMPLE CLEAN SWIFT 3 VERSION

    I like more control over my sounds so I'm using AVFoundation.

    import AVFoundation
    
    class TodayViewController: UIViewController {
    
      var clink: AVAudioPlayer?
      var shatter: AVAudioPlayer?
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        // initialize the sound
        shatter = setupAudioPlayer(withFile: "shatter", type: "wav")
        clink = setupAudioPlayer(withFile: "clink", type: "wav")
      }
    
      func setupAudioPlayer(withFile file: String, type: String) -> AVAudioPlayer? {
        let path = Bundle.main.path(forResource: file, ofType: type)
        let url = NSURL.fileURL(withPath: path!)
        return try? AVAudioPlayer(contentsOf: url)
      }
    
      func onClick() {
        clink?.play()
      }
    }
    

    Make sure you sound file is added to your project and you import AVFoundation.

    0 讨论(0)
  • 2020-11-27 11:09

    Please refer to Simple iOS audio playback

    - (void)playSound
    {
        SystemSoundID soundId;
    
    //    NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"sample"
    //                                              withExtension:@"caf"];
    //    AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &soundId);
    
        NSString *path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"mp3"];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundId);
        AudioServicesAddSystemSoundCompletion(soundId,
                                          NULL,
                                          NULL,
                                          systemAudioCallback,
                                          NULL);
        AudioServicesPlaySystemSound(soundId);
        //AudioServicesPlayAlertSound(soundId);
    }
    
    - (void) systemAudioCallback(SystemSoundID soundId, void *clientData)
    {
        AudioServicesRemoveSystemSoundCompletion(soundId);
        AudioServicesDisposeSystemSoundID(soundId);
    }
    
    0 讨论(0)
  • 2020-11-27 11:11

    From Sound does only work on Device but not in Simulator

    Nick created a library which can be used for playing sounds in iOS and Mac Apps.

    See nicklockwood/SoundManager

    0 讨论(0)
  • 2020-11-27 11:21

    Swift

    The other answers here use Objective-C so I am providing a Swift version here. Swift uses Automatic Reference Counting (ARC), so I am not aware of any memory leak issues with this answer (as warned about in the accepted answer).

    Using AudioToolbox

    You can use the AudioToolbox framework to play short sounds when you do not need much control over how they are played.

    Here is how you would set it up:

    import UIKit
    import AudioToolbox
    
    class PlaySoundViewController: UIViewController {
    
        var soundURL: NSURL?
        var soundID: SystemSoundID = 0
        
        @IBAction func playSoundButtonTapped(sender: AnyObject) {
            
            let filePath = NSBundle.mainBundle().pathForResource("yourAudioFileName", ofType: "mp3")
            soundURL = NSURL(fileURLWithPath: filePath!)
            if let url = soundURL {
                AudioServicesCreateSystemSoundID(url, &soundID)
                AudioServicesPlaySystemSound(soundID)
            }
        }
    }
    

    Notes:

    • This example is adapted from How to play a short sound clip with AudioToolbox in Swift.
    • Remember to add yourAudioFileName.mp3 (or .wav, etc) to your project.
    • Remember to import AudioToolbox
    • This answer puts the code in an IBAction button tap, but it could just as easily be put in another function, of course.

    Using AVAudioPlayer

    By importing the AVFoundation framework, you can use AVAudioPlayer. It works for both short audio clips and long songs. You also have more control over the playback than you did with the AudioToolbox method.

    Here is how you would set it up:

    import UIKit
    import AVFoundation
    
    class PlaySoundViewController: UIViewController {
        
        var mySound: AVAudioPlayer?
        
        // a button that plays a sound
        @IBAction func playSoundButtonTapped(sender: AnyObject) {
            mySound?.play() // ignored if nil
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            // initialize the sound
            if let sound = self.setupAudioPlayerWithFile("yourAudioFileName", type: "mp3") {
                self.mySound = sound
            }
        }
        
        func setupAudioPlayerWithFile(file: NSString, type: NSString) -> AVAudioPlayer? {
            
            let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
            let url = NSURL.fileURLWithPath(path!)
            var audioPlayer: AVAudioPlayer?
            do {
                try audioPlayer = AVAudioPlayer(contentsOfURL: url)
            } catch {
                print("Player not available")
            }
            
            return audioPlayer
        }
    }
    

    Notes:

    • This example is adapted from Learn To Code iOS Apps With Swift Tutorial 5: Making it Beautiful (Adding Sound)
    • Remember to import AVFoundtation and to add yourAudioFileName.mp3 to your project.
    0 讨论(0)
提交回复
热议问题