【问题标题】:playing audio when apps running应用程序运行时播放音频
【发布时间】:2012-07-06 00:25:07
【问题描述】:

我最近一直在尝试让我的应用从打开到关闭时播放声音,但我遇到了困难。当我按下按钮时,我有一些关于播放声音的代码,这很好并制作我玩游戏的声音循环。

.h

#import <AudioToolbox/AudioToolbox.h>


    - (IBAction)t1:(id)sender;

.m

- (IBAction)t1:(id)sender {

    CFBundleRef mainbundle = CFBundleGetMainBundle();
    CFURLRef soundFileUrlRef;
    soundFileUrlRef = CFBundleCopyResourceURL(mainbundle, (CFStringRef) @"t1", CFSTR ("wav"), NULL); 
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileUrlRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}

【问题讨论】:

    标签: ios audio xcode4 xcode4.3


    【解决方案1】:

    如何尝试 AVAudioPlayer 并通过将循环数设置为 -1 来打开连续播放:

        myPlayer.numberOfLoops = -1
    
        [myPlayer prepareToPlay];
    
        [myPlayer play];
    
    
        //when application did enter background or something
        [myPlayer stop];
    

    http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html

    还要确保您的音频会话设置正确以进行后台播放: http://developer.apple.com/library/ios/#DOCUMENTATION/Audio/Conceptual/AudioSessionProgrammingGuide/Basics/Basics.html#//apple_ref/doc/uid/TP40007875-CH2-SW2

    【讨论】:

    • 你需要初始化音频播放器并给它一个源音频文件......像这样: AVAudioPlayer *myPlayer = [[AVAudioPlayer alloc] initWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle ] pathForResource:@"audioFile" ofType:@"wav"]] error:nil];
    • 另外,您可能希望将播放器设置为类属性,以便可以从多个位置访问它,在这种情况下,您可能拥有 self.myPlayer 或 _myPlayer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    相关资源
    最近更新 更多